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].
?
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix==null || matrix.length<=0 || matrix[0].length<=0) {
return res;
}
int start = 0;
while (matrix.length>start*2 && matrix[0].length>start*2) {
solve(matrix, start, res);
start++;
}
return res;
}
private void solve(int[][] matrix, int start, List<Integer> res) {
int endx = matrix[0].length-1-start;
int endy = matrix.length-1-start;
for (int i = start; i <= endx; i++) {
res.add(matrix[start][i]);
}
if (start < endy) {
for (int i = start+1; i <= endy; i++) {
res.add(matrix[i][endx]);
}
}
if (start<endx && start<endy) {
for (int i = endx-1; i >= start; i--) {
res.add(matrix[endy][i]);
}
}
if (start<endx && start<endy-1) {
for (int i = endy-1; i >= start+1; i--) {
res.add(matrix[i][start]);
}
}
}
}
?
原文:http://hcx2013.iteye.com/blog/2221008