59. 螺旋矩阵 II 这道题困扰了我很久,一些边界值控制比较繁琐,但是偶然发现按照以下方法写,在Leetcode可以AC。

class Solution {
    public static int[][] generateMatrix(int n) {
        int num = 1;
        int x = 0;
        int y = 0;
        int[][] res = new int[n][n];
        //判断下一个是不是0,如果是。那么就要“转弯”了
        while(num < n * n){
            while(y < n - 1 && res[x][y + 1] == 0){
                res[x][y] = num++;
                y++;
            }
            while(x < n - 1 && res[x + 1][y] == 0){
                res[x][y] = num++;
                x++;
            }
            while(y > 0 && res[x][y - 1] == 0){
                res[x][y] = num++;
                y--;
            }
            while(x > 0 && res[x - 1][y] == 0){
                res[x][y] = num++;
                x--;
            }
        }
        //最后一个特殊处理,因为不能通过下一个是否是零来判断
        //所以while循环的判断条件是num < n * n
        res[x][y] = num;
        return res;
    }
}

在此记录一下,以防以后忘记。