美文网首页ACM题库~
LeetCode 59. Spiral Matrix II

LeetCode 59. Spiral Matrix II

作者: 关玮琳linSir | 来源:发表于2017-09-26 14:13 被阅读6次

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

相关文章

网友评论

    本文标题:LeetCode 59. Spiral Matrix II

    本文链接:https://www.haomeiwen.com/subject/omusextx.html