举一反三之上链接:
https://leetcode-cn.com/problems/spiral-matrix/
上代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
//m是行数 =3,n是列数 =4
int m = matrix.length;
int n = matrix[0].length;
int c = 0, j = 0;
while(c <= m * n){
for(int i = j; i < n - j; i++){
res.add(matrix[j][i]);
c++;
}
if(c == m*n) break;
for(int i = j + 1; i < m - j; i++){
res.add(matrix[i][n - j - 1]);
c++;
}
if(c == m*n) break;
for(int i = n - j - 2; i >= j; i--){
res.add(matrix[m - j - 1][i]);
c++;
}
if(c == m*n) break;
for(int i = m - j - 2; i > j; i--){
res.add(matrix[i][j]);
c++;
}
j++;
}
return res;
}
}
Easy
剑指offer链接:
https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
上代码:
class Solution {
public int[] spiralOrder(int[][] matrix) {
//m是行数 =3,n是列数 =4
int m = matrix.length;
if(m == 0){
int[] res = new int[]{};
return res;
}
int n = matrix[0].length;
int[] res = new int[m * n];
int c = 0, j = 0;
while(c <= m * n){
for(int i = j; i < n - j; i++){
res[c++] = (matrix[j][i]);
}
if(c == m*n) break;
for(int i = j + 1; i < m - j; i++){
res[c++] = (matrix[i][n - j - 1]);
}
if(c == m*n) break;
for(int i = n - j - 2; i >= j; i--){
res[c++] = (matrix[m - j - 1][i]);
}
if(c == m*n) break;
for(int i = m - j - 2; i > j; i--){
res[c++] = (matrix[i][j]);
}
j++;
}
return res;
}
}
区别在于,一个是List<Integer>类型,一个是一维数组类型,后者测试用例有个空数组,需要在开头追加一个判断。
矩阵螺旋顺序遍历与实现
该博客介绍了如何实现矩阵的螺旋顺序遍历,分别给出了LeetCode上的两种解法,一种返回List<Integer>,另一种返回一维数组。代码中包含了四个循环来按螺旋顺序填充结果,并在每层结束后调整循环边界。同时,对于空矩阵的情况,第二种解法做了额外的判断处理。
9176

被折叠的 条评论
为什么被折叠?



