29. Print matrix clockwise (spiralOrder)
1. python
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
left,top=0,0;
right=len(matrix[0])
bottom=len(matrix)
ans=[]
k =0
while left<right and top<bottom:
#from left to right
for j in range(left,right):
ans.append(matrix[top][j])
top+=1
#from top to bottom
for i in range(top,bottom):
ans.append(matrix[i][right-1])
right-=1
#from right to left
for j in range(right-1,left-1,-1):
if(top<bottom):
ans.append(matrix[bottom-1][j])
bottom-=1
#from bottom to top
for i in range(bottom-1,top-1,-1):
if(left<right):
ans.append(matrix[i][left])
left+=1
return ans
2. Java
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length ==0 ||matrix==null){
return new int[0];
}
int left=0;
int top=0;
int right=matrix[0].length;
int bottom=matrix.length;
int[] ans = new int[right*bottom];
int k=0;
while(left<right && top<bottom){
for(int j=left;j<right;j++){
ans[k++]=matrix[top][j];
}
top++;
for(int i =top;i<bottom;i++){
ans[k++]=matrix[i][right-1];
}
right--;
for(int j=right-1;j>=left && top<bottom;j--){
ans[k++]=matrix[bottom-1][j];
}
bottom--;
for(int i=bottom-1;i>=top && left<right;i--){
ans[k++]=matrix[i][left];
}
left++;
}
return ans;
}
}