2021.11.14 - 150.打印回形数

1. 题目

在这里插入图片描述

2. 思路

(1) 模拟法

  • 模拟顺时针遍历二维数组的过程。
  • 注意!这道题是ACM模式,需要自己从控制台接收输入的参数。

3. 代码

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();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121322323