Lintcode: Matrix Zigzag Traversal

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

 1 public class Solution {
 2     /**
 3      * @param matrix: a matrix of integers
 4      * @return: an array of integers
 5      */ 
 6     public int[] printZMatrix(int[][] matrix) {
 7         // write your code here
 8         if (matrix==null || matrix.length==0 || matrix[0].length==0) return null;
 9         int m = matrix.length;
10         int n = matrix[0].length;
11         int count = m*n;
12         int[] res = new int[count];
13         int x=0, y=0;
14         for (int i=0; i<count;) {
15             while (x>=0 && y<n) {
16                 res[i++] = matrix[x--][y++];
17             }
18             if (i == count) break;
19             if (x<0 && y<n) {
20                 x++;
21             }
22             else {
23                 x = x+2;
24                 y = y-1;
25             }
26             while (x<m && y>=0) {
27                 res[i++] = matrix[x++][y--];
28             }
29             if (i == count) break;
30             if (x<m && y<0) {
31                 y++;
32             }
33             else {
34                 x = x-1;
35                 y = y+2;
36             }
37         }
38         return res;
39     }
40 }

 

你可能感兴趣的:(Lintcode: Matrix Zigzag Traversal)