4.13
这道题简直要写懵逼了啊。
要搞清楚运动方向。
public class Solution { /** * @param matrix: a matrix of integers * @return: an array of integers */ public static int[] printZMatrix(int[][] matrix) { if(matrix == null){ return null;// write your code here } int n = matrix.length; if(n == 1){ return matrix[0]; } int m = matrix[0].length; int num = m*n; boolean[][] flag = new boolean[n][m]; int[] res = new int[ num ]; if( m == 1){ for(int k = 0;k < n; k++){ res[k] = matrix[k][0]; } return res; } res[0] = matrix[0][0]; res[1] = matrix[0][1]; int i = 0; int j = 1; int count = 1; while(count < num){ //向斜下方运动 while( i < n-1 && j > 0 && count < num-1){ res[++count] = matrix[++i][--j]; if(i == n-1 && j== m-1){ res[ ++count] = matrix[i][j]; return res; } } //向右运动 if(i == n-1 && j < m-1){ res[ ++count] = matrix[i][++j]; } // 向下运动 if( j == 0 && i < n-1){ res[++count] = matrix[++i][j]; } //向斜上方运动 while(i > 0 && j < m-1 && count < num-1){ res[++count] = matrix[--i][++j]; } //向下移动 if(j == m-1 && i < n-1){ res[++count] = matrix[++i][j]; } if(j == m-1 && i == n-1){ res[count++] = matrix[i][j]; return res; } //向右移动 if(i == 0 && j < m-1){ res[++count] = matrix[i][++j]; } } return res; } }