算法 - 螺旋矩阵 II

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

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

本文作者:护发师兄

本文链接:https://www.cnblogs.com/jonil/p/16643635.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   护发师兄  阅读(28)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起