1、
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.
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]
2、不懂:
/** * @param matrix: a matrix of integers * @return: an array of integers */ public int[] printZMatrix(int[][] matrix) { // write your code here int x, y, dx, dy, count, m, n; x = y = 0; count = 1; dx = -1; dy = 1; m = matrix.length; n = matrix[0].length; int[] z = new int[m*n]; z[0] = matrix[0][0]; while (count<m*n) { if (x+dx>=0 && y+dy>=0 && x+dx<m && y+dy<n) { x += dx; y += dy; } else if (dx==-1 && dy ==1) { if (y+1<n) ++y; else ++x; dx = 1; dy = -1; } else { if (x+1<m) ++x; else ++y; dx = -1; dy = 1; } z[count] = matrix[x][y]; ++count; } return z; }
时间: 2024-11-02 23:31:18