leetcode59. Spiral Matrix II

来源:互联网 发布:调查问卷数据分析方法 编辑:程序博客网 时间:2024/06/05 09:37

59.Spiral Matrix II

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,将1-n^2数分别顺时针从最外层到里层直到最中间格子。

思路:总循环当num<=n^2,及格子未填满

每填一个格子都要判断该格子是否已填。条件mart[x][y]==0 

依次 1.填上面一行 2.填右边·一行 3.填下面一行 4.填左边一行

AC代码:

public int[][] generateMatrix(int n) {
        int[][]  mart=new int [n][n];
        int squre=n*n;
        int x=0,y=0;
        int num=1;
        while(num<=squre){
            while(y<n&&mart[x][y]==0){
                mart[x][y]=num;
                y++;
                num++;
            }
            y--;
            x++;
            while(x<n&&mart[x][y]==0){
                mart[x][y]=num;
                x++;
                num++;
            }
            x--;
            y--;
            while(y>=0&&mart[x][y]==0){
                mart[x][y]=num;
                y--;
                num++;
            }
            y++;
            x--;
            while(x>=0&&mart[x][y]==0){
                mart[x][y]=num;
                x--;
                num++;
            }
            x++;
            y++;
        }
        return mart;
    }