蛇形矩陣

直接上代碼:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        sc.close();
        int row = 0, col = 0;
        int top = 0, left = -1, right = n - 1, bottom = n - 1;
        int[][] arr = new int[n][n];
        int num = 0;
        while(num<n*n){
            for (int j = ++left; j <= right; j++) {
                col = j;
                arr[row][col] = ++num;
            }
            for (int k = ++top; k <= bottom; k++) {
                row = k;
                arr[row][col] = ++num;
            }
            for (int j = --right; j >= left; j--) {
                col = j;
                arr[row][col] = ++num;
            }
            for (int k = --bottom; k >= top; k--) {
                row = k;
                arr[row][col] = ++num;
            }
        }
        for(int i=0; i<n;i++){
            for(int j=0; j<n;j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}

輸入n=6;
輸出結果應該爲:

1 2 3 4 5 6 
20 21 22 23 24 7 
19 32 33 34 25 8 
18 31 36 35 26 9 
17 30 29 28 27 10 
16 15 14 13 12 11

Game Over

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章