Matrix Zigzag Traversal
Given a matrix of m x n elements (m rows, ncolumns), 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]
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 int m = matrix.length; 8 int n = matrix[0].length; 9 int l = matrix.length*matrix[0].length; 10 int[] result = new int[l]; 11 12 int d = -1; 13 int x = 0; 14 int y = 0; 15 for(int i=0;i<l;i++) { 16 result[i] = matrix[x][y]; 17 18 if(x+d < 0 && y < n-1 || x+d >= m && y >= 0) { 19 d = -d; 20 y++; 21 }else { 22 if(y-d < 0 && x < m-1 || y-d >= n && x >= 0) { 23 d = -d; 24 x++; 25 }else { 26 x = x + d; 27 y = y - d; 28 } 29 } 30 } 31 32 return result; 33 } 34 }
时间: 2024-11-16 15:17:41