ACM题库~

LeetCode 59. Spiral Matrix II

2017-09-26  本文已影响6人  关玮琳linSir

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题意,给我们一个n,求解出n*n的矩阵,同时填充数字,循环填充。

代码:

public int[][] generateMatrix(int n) {

        int total = n*n;
        int[][] result= new int[n][n];
     
        int x=0;
        int y=0;
        int step = 0;
     
        for(int i=0;i<total;){
            while(y+step<n){
                i++;
                result[x][y]=i; 
                y++;
     
            }    
            y--;
            x++;
     
            while(x+step<n){
                i++;
                result[x][y]=i;
                x++;
            }
            x--;
            y--;
     
            while(y>=0+step){
                i++;
                result[x][y]=i;
                y--;
            }
            y++;
            x--;
            step++;
     
            while(x>=0+step){
                i++;
                result[x][y]=i;
                x--;
            }
            x++;
            y++;
        }
     
        return result;
    }

上一篇 下一篇

猜你喜欢

热点阅读