题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> result = new ArrayList<>(); int x1 = 0, y1 = 0; int x2 = 0, y2 = matrix[0].length - 1; int x3 = matrix.length - 1, y3 = matrix[0].length - 1; int x4 = matrix.length - 1, y4 = 0; while(x1<x4 && y1<y2){ // 当出现横着一条或竖着一条的时候,停止遍历 int p1 = x1, p2 = y1; //向右走 while(p2 < y2){ result.add(matrix[p1][p2]); p1 = p1; p2 = p2 + 1; } //向下走 while(p1<x3){ result.add(matrix[p1][p2]); p1 = p1 + 1; p2 = p2; } //向左走 while(p2>y4){ result.add(matrix[p1][p2]); p1 = p1; p2 = p2 - 1; } //向上走 while(p1>x1){ result.add(matrix[p1][p2]); p1 = p1 - 1; p2 = p2; } //四个定点向里缩 x1 = x1 + 1; y1 = y1 + 1; x2 = x2 + 1; y2 = y2 - 1; x3 = x3 - 1; y3 = y3 - 1; x4 = x4 - 1; y4 = y4 + 1; } //如果最后剩了横条 if(x1 == x4){ while(y1 <= y2){ result.add(matrix[x1][y1]); x1 = x1; y1 = y1 + 1; } } //如果最后剩了竖条 else if(y1 == y2){ while(x1 <= x4){ result.add(matrix[x1][y1]); x1 = x1 + 1; y1 = y1; } } return result; } }