当前位置:网站首页>2022.02.13 - NC004. Print number of loops

2022.02.13 - NC004. Print number of loops

2022-07-06 08:21:00 A CAI continues to work hard

1. subject

 Insert picture description here

2. Ideas

(1) Simulation

  • Simulate the process of traversing a two-dimensional array clockwise .
  • Be careful ! The question is ACM Pattern , You need to receive the input parameters from the console .

3. Code

import java.util.Scanner;

public class Main {
    
    public static int width;
    public static int height;
    public static int[][] array;
    public static int left;
    public static int right;
    public static int up;
    public static int down;
    public static int curNum;

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        width = scanner.nextInt();
        height = scanner.nextInt();
        array = new int[height][width];
        left = -1;
        right = width;
        up = -1;
        down = height;
        curNum = 0;
        moveRight();
        for (int[] ints : array) {
    
            for (int anInt : ints) {
    
                System.out.print(anInt);
            }
            System.out.println();
        }
    }

    public static void moveRight() {
    
        if (left + 1 == right) {
    
            return;
        }
        for (int i = left + 1; i < right; i++) {
    
            array[up + 1][i] = curNum;

        }
        curNum++;
        up++;
        moveDown();
    }

    public static void moveDown() {
    
        if (up + 1 == down) {
    
            return;
        }
        for (int i = up + 1; i < down; i++) {
    
            array[i][right - 1] = curNum;

        }
        curNum++;
        right--;
        moveLeft();
    }

    public static void moveLeft() {
    
        if (right - 1 == left) {
    
            return;
        }
        for (int i = right - 1; i > left; i--) {
    
            array[down - 1][i] = curNum;

        }
        curNum++;
        down--;
        moveUp();
    }

    public static void moveUp() {
    
        if (down - 1 == up) {
    
            return;
        }
        for (int i = down - 1; i > up; i--) {
    
            array[i][left + 1] = curNum;

        }
        curNum++;
        left++;
        moveRight();
    }
}
原网站

版权声明
本文为[A CAI continues to work hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131832390350.html