[LeetCode] 59. Spiral Matrix II Java

题目:

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*n之间的数。从左到右,从上到下,从右到左,从下到上,按顺序递增。

代码:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if(n==0) return res;
        int k = 1;
        res[0][0] = 1;
        generate(res,k,n,0,0,0);
        return res;
    }


    private void generate(int[][] res,int k,int n,int i,int j,int direction){     //0代表右,1代表下,2代表左,3代表上
        while(k<n*n){
            if(direction == 0){ //
                while(j<n-1 && res[i][j+1]==0){
                    res[i][j+1] = ++k;
                    j++;
                }
                direction = 1;
            }else if(direction==1){     //
                while(i<n-1 && res[i+1][j]==0){
                    res[i+1][j] = ++k;
                    i++;
                }
                direction = 2;
            }else if(direction==2){
                while(j>0 && res[i][j-1]==0){
                    res[i][j-1] = ++k;
                    j--;
                }
                direction = 3;
            }else{
                while(i>0 && res[i-1][j]==0){
                    res[i-1][j] = ++k;
                    i--;
                }
                direction = 0;
            }
        }
    }
}

 

posted @ 2018-01-15 14:39  荒野第一快递员  阅读(123)  评论(0编辑  收藏  举报