牛客题霸NC31转圈打印矩阵Java题解
转圈打印矩阵
http://www.nowcoder.com/questionTerminal/fe219d47475842e68e64ba6fea42b846
牛客题霸NC31转圈打印矩阵Java题解
https://www.nowcoder.com/practice/fe219d47475842e68e64ba6fea42b846?tpId=117&&tqId=35276&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
方法:逐个遍历
解题思路:按照从左到右、从上到下、从右到左、从下到上的顺序依此遍历。
import java.util.*; public class Solution { /** * * @param matrix int整型二维数组 the matrix * @return int整型一维数组 */ public int[] printMatrix (int[][] matrix) { if(matrix.length == 0) { return null; } int left = 0; int right = matrix[0].length - 1; int top = 0; int bottom = matrix.length - 1; int x = 0; int[] res = new int[(right + 1) * (bottom + 1)]; while(true) { for(int i = left; i <= right; i++) { //从左到右 res[x++] = matrix[top][i]; } if(++top > bottom){ break; } for(int i = top; i <= bottom; i++){ // 从上到下 res[x++] = matrix[i][right]; } if(left > --right){ break; } for(int i = right; i >= left; i--){ //从右到左 res[x++] = matrix[bottom][i]; } if(top > --bottom){ break; } for(int i = bottom; i >= top; i--){ //从下到上 res[x++] = matrix[i][left]; } if(++left > right){ break; } } return res; } }