您的位置:首页 > 其它

Lintcode: Matrix Zigzag Traversal

2016-02-01 05:24 375 查看
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.

Have you met this question in a real interview? Yes
Example
Given a matrix:

[
[1, 2,  3,  4],
[5, 6,  7,  8],
[9,10, 11, 12]
]
return [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]

Tags Expand


先斜上走到顶,再斜下走到底,直到计数器满, 写的时候老是fail,才发现14行for循环i不需要++,循环里面自己加了

注意corner cases, 以斜上为例

如果是

1,2

5,6

9,10

中6的这种情况,下一个点是10,则x = x+2, y=y-1

如果是1这种情况, 下一个点是2,则只需x = x+1

public class Solution {
/**
* @param matrix: a matrix of integers
* @return: an array of integers
*/
public int[] printZMatrix(int[][] matrix) {
// write your code here
if (matrix==null || matrix.length==0 || matrix[0].length==0) return null;
int m = matrix.length;
int n = matrix[0].length;
int count = m*n;
int[] res = new int[count];
int x=0, y=0;
for (int i=0; i<count;) {
while (x>=0 && y<n) {
res[i++] = matrix[x--][y++];
}
if (i == count) break;
if (x<0 && y<n) {
x++;
}
else {
x = x+2;
y = y-1;
}
while (x<m && y>=0) {
res[i++] = matrix[x++][y--];
}
if (i == count) break;
if (x<m && y<0) {
y++;
}
else {
x = x-1;
y = y+2;
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: