給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。
示例 1:
輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例 2:
輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix.length==0||matrix==null)
return res;
int m = matrix.length;
int n = matrix[0].length;
int l = m*n;
int i=0,j=0;
boolean visited[][] = new boolean[matrix.length][matrix[0].length];
while(true){
if(res.size()==l){
break;
}
while(j<n&&visited[i][j]!=true&&res.size()<l){
res.add(matrix[i][j]);
visited[i][j] = true;
j++;
}
j--;
i++;
while(i<m&&visited[i][j]!=true&&res.size()<l){
res.add(matrix[i][j]);
visited[i][j] = true;
i++;
}
i--;
j--;
while(j>=0&&visited[i][j]!=true&&res.size()<l){
res.add(matrix[i][j]);
visited[i][j] = true;
j--;
}
j++;
i--;
while(i>=0&&visited[i][j]!=true&&res.size()<l){
res.add(matrix[i][j]);
visited[i][j] = true;
i--;
}
i++;
j++;
}
return res;
}