题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
简单想法:
算把外围的一圈(0, 0) (x, 0) (x, y), (0, y)打印出来;
然后打印内圈(1, 1)(x1-1, 1) (x-1, y-1), (0, y-1);
逐圈打印;
这种特殊情况:
1,2,3
或者
1,
2,
3
这几种。
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> res = new ArrayList(); if (matrix == null || matrix.length == 0) { return res; } int rows = matrix.length - 1; int cols = matrix[0].length - 1; print(matrix, 0, 0, cols, rows, res); return res; } private void print(int [][] matrix, int x1, int y1, int x2, int y2, ArrayList<Integer> res) { if (x1 > x2 || y1 > y2) { return; } for (int i = x1; i <= x2; i++) { res.add(matrix[y1][i]); } for (int i = y1 + 1; i <= y2 -1; i++) { res.add(matrix[i][x2]); } if (y2 > y1) { for (int i = x2; i >= x1; i--) { res.add(matrix[y2][i]); } } if (x2 > x1) { for (int i = y2 - 1; i >= y1 + 1; i--) { res.add(matrix[i][x1]); } } print(matrix, x1+1, y1+1, x2-1, y2-1, res); } }