矩阵的之字型遍历
题目
给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。
样例
对于如下矩阵:
返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]题解
public class Solution {
/**
* @param matrix: a matrix of integers
* @return: an array of integers
*/
public int[] printZMatrix(int[][] matrix) {
int[] result = new int[matrix.length * matrix[0].length];
int i = 0;
int j = 0;
int count = 1;
result[0] = matrix[0][0];
while (count < result.length)
{
//向右移动一格或向下移动一格
result[count++] = j<matrix[0].length-1?matrix[i][++j]:matrix[++i][j];
if (count == result.length)
{
break;
}
//转到左下
while (i<matrix.length-1 && j>0)
{
result[count++] = matrix[++i][--j];
}
//如果可以下移则下移,否则右移一格
result[count++] = i<matrix.length-1?matrix[++i][j]:matrix[i][++j];
//转到右上
while (i > 0 && j < matrix[0].length-1)
{
result[count++] = matrix[--i][++j];
}
}
return result;
}
}
Last Update 2016.9.9