题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
题解
这个题目就是正常的模拟就好。
定义四个变量。top: 表示最上面的行;bottom:表示最小面的行;left:表示最左边的列;right: 表示最右边的列;- 左 -> 右,这个时候相当于最上面这一行就打印完了,这个时候最上面的行top要++;
- 右 -> 下,这个时候相当于最右边这一列就打印完了,这个时候最右边的列right要--;
- 右 -> 左,这个时候相当于最下边这一行就打印完了,这个时候最下边的行bottom要--;
- 下 -> 上,这个时候相当于最左边这一列就打印完了,这个时候最左边的列left要--;
但是每一步完成之后可能都会遇到边界条件:
1 2 3 4
比如上面这个case,top++之后就应该跳出循环,不应该继续走了。
1234
再比如上面这个case,走到right--之后就应该跳出循环,不应该继续走了。
此外还要注意判断一下矩阵是null的情况。
import java.util.ArrayList;public class Solution { public ArrayListprintMatrix(int [][] matrix) { if (matrix == null) return new ArrayList(); int top = 0; int bottom = matrix.length - 1; int left = 0; int right = matrix[0].length - 1; ArrayList result = new ArrayList(); while (top <= bottom && left <= right) { for (int i = left; i <= right; i++) { result.add(matrix[top][i]); } top++; if (top > bottom) { break; } for (int i = top; i <= bottom; i++) { result.add(matrix[i][right]); } right--; if (left > right) { break; } for (int i = right; i >= left; i--) { result.add(matrix[bottom][i]); } bottom--; if (top > bottom) { break; } for (int i = bottom; i >= top; i--) { result.add(matrix[i][left]); } left++; if (left > right) { break; } } return result; }}