题目链接:
LeetCode 54 — Spiral Matrix
AC代码:
//参考 https://discuss.leetcode.com/topic/64099/easy-java-solution-with-explaination
public class Problem54 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> re = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) return re;
int m = matrix.length;
int n = matrix[0].length;
int start = 0;
int upRow = 0, boRow = m-1, leCol = 0, riCol = n-1;
while(true){
for(int i = start; i <= riCol; i++){
re.add(matrix[upRow][i]);
}
if(re.size() == m*n) return re;
start++;
for(int i = start; i <= boRow; i++){
re.add(matrix[i][riCol]);
}
if(re.size() == m*n) return re;
for(int i = n - 1 - start; i >= leCol; i--){
re.add(matrix[boRow][i]);
}
if(re.size() == m*n) return re;
for(int i = m - 1 - start; i > upRow; i--){
re.add(matrix[i][leCol]);
}
if(re.size() == m*n) return re;
riCol--; boRow--; leCol++; upRow++;
}
}
}