实现
方法1:Java 和力扣的54一摸一样,除了需要考虑[]的输入。
1、List初始化
import java.util.ArrayList; import java.util.List;
ArrayList list = new ArrayList<>();
2、二维数组判断是否为空: 横1竖0
if((arraynull || array.length0) || (array.length1 && array[0].length0))
3、判断[]
if (matrix.length==0){ }
4、思路:想象4个小棒把数组框起来。
import java.util.ArrayList;
import java.util.List;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList <Integer> list = new ArrayList<>();
if (matrix.length==0){
return list;
}
int left=0;
int top=0;
int bottom=matrix.length - 1;
int right=matrix[0].length - 1;
while(true){
for (int i=left; i<=right; i++){
list.add(matrix[top][i]);
}
top++;
if (top>bottom){
break;
}
for (int i=top; i<=bottom; i++){
list.add(matrix[i][right]);
}
right--;
if (left>right){
break;
}
for (int i=right; i>=left; i--){
list.add(matrix[bottom][i]);
}
bottom--;
if (top>bottom){
break;
}
for (int i=bottom; i>=top; i--){
list.add(matrix[i][left]);
}
left++;
if (left>right){
break;
}
}
return list;
}
}
方法2:python
class Solution:
def spiralOrder(self , matrix ):
res=list()
if len(matrix)==0: return matrix
left,top=0,0
right=len(matrix[0])-1
bottom=len(matrix)-1
while(True):
for i in range(left,right+1):
res.append(matrix[top][i])
top+=1
if top>bottom: break
for i in range(top,bottom+1):
res.append(matrix[i][right])
right-=1
if right<left: break
for i in range(right,left-1,-1):
res.append(matrix[bottom][i])
bottom-=1
if top>bottom: break
for i in range(bottom,top-1,-1):
res.append(matrix[i][left])
left+=1
if left>right: break
return res
|