class Solution {
private List<Integer> retlist = new LinkedList<>();
private int rowlength;
private int columnlength;
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix.length==0){
return this.retlist;
}
this.rowlength = matrix.length;
this.columnlength = matrix[0].length;
int index = 0;
int maxcount = matrix[0].length*matrix.length;
this.dfs(0,0,matrix,1,maxcount,0);
return this.retlist;
}
public void dfs(int row,int column,int[][] matrix,int order,int maxcount,int index){
this.retlist.add(matrix[row][column]);
index+=1;
if(maxcount==index){
return;
}
//接下来判断方向
//1是右,2是左,3是上,4是下
if(order==1){
if(column+1+row<columnlength){
this.dfs(row,column+1,matrix,order,maxcount,index);
}
else{
this.dfs(row+1,column,matrix,4,maxcount,index);
}
}
if(order==4){
if(columnlength-column+row<rowlength){
this.dfs(row+1,column,matrix,4,maxcount,index);
}
else{
this.dfs(row,column-1,matrix,2,maxcount,index);
}
}
if(order==2){
if(column>rowlength-row-1){
this.dfs(row,column-1,matrix,2,maxcount,index);
}
else{
this.dfs(row-1,column,matrix,3,maxcount,index);
}
}
if(order==3){
if(row-1>=column+1){
this.dfs(row-1,column,matrix,3,maxcount,index);
}
else{
this.dfs(row,column+1,matrix,1,maxcount,index);
}
}
}
}
这道题的关键就是确定边界转折点,其实这类边界的确定可以这样想。先把当前的row和column写出来,然后找和相应的rowlength,columnlength的关系即可
来源:CSDN
作者:dogndaxiaodong
链接:https://blog.csdn.net/weixin_41327340/article/details/103788291