29.顺时针打印矩阵
大约 1 分钟
29.顺时针打印矩阵
参考链接
剑指 Offer 29. 顺时针打印矩阵-跟着帅地玩转校招,刷爆各类算法题帅地玩Offer
LCR 146. 螺旋遍历二维数组 - 力扣(LeetCode)
优秀题解
class Solution {
public int[] spiralArray(int[][] array) {
if(array.length == 0) return new int[0];
int l = 0, r = array[0].length - 1, t = 0, b = array.length - 1, x = 0;
int[] res = new int[(r + 1) * (b + 1)];
while(true) {
for(int i = l; i <= r; i++) res[x++] = array[t][i]; // left to right
if(++t > b) break;
for(int i = t; i <= b; i++) res[x++] = array[i][r]; // top to bottom
if(l > --r) break;
for(int i = r; i >= l; i--) res[x++] = array[b][i]; // right to left
if(t > --b) break;
for(int i = b; i >= t; i--) res[x++] = array[i][l]; // bottom to top
if(++l > r) break;
}
return res;
}
}
作者:Krahets
链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solutions/129360/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
个人理解:
由左到右,array[t][]
行索引 不变, 列索引 变化,遍历了 top 的一行,top加一,判断 top >? bottom
由上到下,array[][r]
列索引 不变,行索引 变化,遍历 right 的一列,right 减一,判断 right <? left
由右到左,array[b][]
行索引 不变,列索引 变化,遍历 bottom 的一行,bottom 减一,判断 bottom <? top
由下到上,array[][l]
列索引 不变,行索引 变化,遍历 left 的一列,left 加一,判断 left >? right