leetCode 59.Spiral Matrix II (螺旋矩阵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 ]

]


思路:此题和螺旋矩阵题差不多,没什么难的地方,主要就是四个方向的转换。

具体代码如下:

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

        int[][] a = new int[n][n];
        int o = 0;//定义方向,0:右;1:下;2:左,3:上
        int x = 0;//1-n2
        int i = 0;//行
        int j = 0;//列
        while(i >= 0 && i < n && j >= 0 && j < n){
        	if(a[i][j] > 0)
        		break;//已全部填满,结束
            a[i][j] = ++x;//填充数据
            switch(o){//很方向讨论情况
                case 0:
                    if(j == n-1 || a[i][j+1] > 0){
                        i++;
                        o = 1;
                    }else{
                        j++;
                    }
                    break;
                case 1:
                    if(i == n-1 || a[i+1][j] > 0){
                        j--;
                        o = 2;
                    }else{
                        i++;
                    }
                    break;
                case 2:
                    if(j == 0 || a[i][j-1] > 0){
                        i--;
                        o = 3;
                    }else{
                        j--;
                    }
                    break;
                case 3:
                    if(i == 0 || a[i-1][j] > 0){
                        j++;
                        o = 0;
                    }else{
                        i--;
                    }
                    break;
            }
        }
        return a;
    }
}


你可能感兴趣的:(leetCode)