您的位置:首页 > 其它

Spiral Matrix

2015-07-24 09:59 357 查看
问题描述

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> path = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return path;
}

int i = 0, j = 0;
int n = matrix.length, m = matrix[0].length;
int cnt = n * m;
int cyc = 0;

while (true) {
// to right
while (j < m - cyc) {
path.add(matrix[i][j++]);
}
--j;
++i;
// to bottom
while (i < n - cyc) {
path.add(matrix[i++][j]);
}
--i;
--j;
if (path.size() == cnt) {
break;
}

// to left
while (j >= cyc) {
path.add(matrix[i][j--]);
}
++j;
--i;
// to top
while (i > cyc) {
path.add(matrix[i--][j]);
}
++i;
++j;
if (path.size() == cnt) {
break;
}

++cyc;
}

return path;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: