您的位置:首页 > 其它

LeetCode: Spiral Matrix 解题报告

2014-10-23 18:39 309 查看
[b]

public List<Integer> spiralOrder3(int[][] matrix) {
List<Integer> ret = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return ret;
}

int rows = matrix.length;
int cols = matrix[0].length;

int left = 0;
int right = cols - 1;
int top = 0;
int bottom = rows - 1;

while (left <= right && top <= bottom) {
// line top.
for (int i = left; i <= right; i++) {
ret.add(matrix[top][i]);
}

// line right;
for (int i = top + 1; i <= bottom - 1; i++) {
ret.add(matrix[i][right]);
}

// line bottom.
if (top != bottom) {
for (int i = right; i >= left; i--) {
ret.add(matrix[bottom][i]);
}
}

// line left;
if (left != right) {
for (int i = bottom - 1; i >= top + 1; i--) {
ret.add(matrix[i][left]);
}
}

left++;
right--;
top++;
bottom--;
}

return ret;
}


View Code

[b][b]GitHub CODE:
[/b]

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