Matrix Zigzag Traversal
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]
http://www.lintcode.com/en/problem/matrix-zigzag-traversal/
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 count = matrix.length * matrix[0].length;
int n = matrix[0].length;
int m = matrix.length;
int[] array = new int[count];
array[0] = matrix[0][0];
int lastr = 0, lastc=0;
int i = 1;
while(i < count){
//morve right or move down
if(lastc + 1 < n || lastr + 1 < m){
if(lastc + 1 < n){
lastc++;
}else{
lastr++;
}
array[i++] = matrix[lastr][lastc];
}
//move to dignaol
while(lastr + 1 < m && lastc - 1 >= 0 ){
array[i++] = matrix[++lastr][--lastc];
}
//move down or right
if(lastc + 1 < n || lastr + 1 < m){
if(lastr + 1 < m){
lastr++;
}else{
lastc++;
}
array[i++] = matrix[lastr][lastc];
}
//move dignoal up
while(lastr - 1 >= 0 && lastc + 1 < n){
array[i++] = matrix[--lastr][++lastc];
}
}
return array;
}
}