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]
.
Code:
/**
*
*/
package From41;
import java.util.LinkedList;
import java.util.List;
/**
* @author MohnSnow
* @time 2015年6月26日 上午11:45:06
* @translate 螺旋序列打印数组
*/
public class LeetCode54 {
/**
* @param argsmengdx
* -fnst
*/
//260msAC---一次性通过----去讨论去看看Discuss----差不多都是递归处理
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> reList = new LinkedList<Integer>();
int row = 0;
int col = 0;
spiralOrder(reList, matrix, row, col);
return reList;
}
public static List<Integer> spiralOrder(List<Integer> reList, int[][] matrix, int row, int col) {
int rowLen = matrix.length - 2 * row;
int rowEnd = matrix.length - row - 1;
if (rowLen == 0 || matrix[0].length - 2 * col == 0) {
return reList;
}
int colLen = matrix[0].length - 2 * col;
int colEnd = matrix[0].length - col - 1;
if (rowLen == 1) {
for (int i = col; i <= colEnd; i++) {
reList.add(matrix[row][i]);
}
} else if (colLen == 1) {
for (int i = row; i <= rowEnd; i++) {
reList.add(matrix[i][col]);
}
} else {
for (int i = col; i <= colEnd; i++) {//上
reList.add(matrix[row][i]);
}
for (int i = row + 1; i <= rowEnd; i++) {//右
reList.add(matrix[i][colEnd]);
}
for (int i = colEnd - 1; i >= col; i--) {//下
reList.add(matrix[rowEnd][i]);
}
//System.out.println("reList: " + reList.toString());
//System.out.println("rowEnd: " + rowEnd);
for (int i = rowEnd - 1; i > row; i--) {//左
reList.add(matrix[i][col]);
}
spiralOrder(reList, matrix, row + 1, col + 1);
}
return reList;
}
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 3, 4 },
{ 4, 5, 6, 6 },
{ 7, 8, 9, 9 }
};
System.out.println("spiralOrder: " + spiralOrder(matrix));
}
}