Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
写的好凌乱啊,下次再重新写一次。
Source
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> st = new ArrayList<Integer>();
if(matrix.length == 0)
return st;
if(matrix.length == 1){
for(int i = 0; i < matrix[0].length; i++)
st.add(matrix[0][i]);
return st;
}
int m, n,cycle;
m = matrix.length;
n = matrix[0].length;
cycle = Math.min(m / 2, n / 2);
for(int i = 0; i < cycle; i++){ //***
for(int j = i; j < n - i; j++){
st.add(matrix[i][j]);
}
for(int j = i + 1; j < m - i; j++){
st.add(matrix[j][n - 1 - i]);
}
for(int j = n - i - 2; j >= i; j--){
st.add(matrix[m - 1 - i][j]);
}
for(int j = m - 2 - i; j > i; j--){
st.add(matrix[j][i]);
}
}
if(st.size() < m*n){ //奇数行 注意只有一行和一列的情况
for(int j = cycle ; j < n - cycle ; j++){
st.add(matrix[cycle][j]);
}
for(int j = cycle + 1; j < m - cycle; j++){
st.add(matrix[j][cycle]);
}
}
return st;
}
public static void main(String[] args){
List<Integer> st = new ArrayList<Integer>();
int[][] matrix = {{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}};
st = new Solution().spiralOrder(matrix);
System.out.println(st);
}