题目链接:https://leetcode.com/problems/spiral-matrix/
本题是矩阵的螺旋遍历,如图:
将四周(蓝色)遍历完成后剩余部分依旧是一个矩形,因此剩余任务跟整个任务的完成方法一致,子矩阵的范围可以由左上角方块坐标和右下角方块坐标唯一确定,可以使用递归!!!
解法如下:
class Solution {
public static int count;
public static int n;
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix==null)
return null;
int n_row=matrix.length,n_col=0;
if(n_row!=0)
n_col=matrix[0].length;
count=0;
n=n_row*n_col;
LinkedList<Integer> ret=new LinkedList<Integer>();
recursion(matrix,0,0,n_row-1,n_col-1,ret);
return ret;
}
public void recursion(int nums[][],int ltx,int lty,int rbx,int rby,LinkedList<Integer> ret)
{
if(ltx>rbx || lty>rby)
return;
for(int i=lty;i<=rby;i++)
{
ret.add(nums[ltx][i]);
count++;
}
for(int j=ltx+1;j<=rbx;j++)
{
ret.add(nums[j][rby]);
count++;
}
if(count>=n)
return;
for(int i=rby-1;i>=lty;i--)
{
ret.add(nums[rbx][i]);
count++;
}
for(int j=rbx-1;j>ltx;j--)
{
ret.add(nums[j][lty]);
count++;
}
recursion(nums,ltx+1,lty+1,rbx-1,rby-1,ret);
}
}
思路相同,非递归解法与官方解法2一致:
class Solution {
public List < Integer > spiralOrder(int[][] matrix) {
List ans = new ArrayList();
if (matrix.length == 0)
return ans;
int r1 = 0, r2 = matrix.length - 1;
int c1 = 0, c2 = matrix[0].length - 1;
while (r1 <= r2 && c1 <= c2) {
for (int c = c1; c <= c2; c++) ans.add(matrix[r1][c]);
for (int r = r1 + 1; r <= r2; r++) ans.add(matrix[r][c2]);
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; c--) ans.add(matrix[r2][c]);
for (int r = r2; r > r1; r--) ans.add(matrix[r][c1]);
}
r1++;
r2--;
c1++;
c2--;
}
return ans;
}
}