题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下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.
思路:
思路:通过判断条件改变方向
1. 每次碰到四个角落就变换前进的方向
2. 变换的方向是顺时针90度
3. 顺时针90°可以,改变一个方向的正负来表示
4. 令当前位置为px, py, 当前速度为dx, dy,
dx dy
向右: 1 0
向下: 0 1
向左: -1 0
向上: 0 -1
5. 变换方向之后需要将对应的边界缩小一格。
代码
public class PrintMatrix {
public static void printMatrix(int[][] matrix) {
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
// 初始状态
int dx = 1;
int dy = 0;
int x = 0;
int y = 0;
while (top <= bottom && left <= right) { // 在还有未遍历完的序列的时候继续
// 控制方向
if (x == right && y == top && dx == 1 && dy == 0) {
// 遇到右上角,并且运动方向是向右
dx = 0;
dy = 1;
top += 1;
} else if (x == right && y == bottom && dx == 0 && dy == 1) {
dx = -1;
dy = 0;
right -= 1;
} else if (x == left && y == bottom && dx == -1 && dy == 0) {
dx = 0;
dy = -1;
bottom -= 1;
} else if (x == left && y == top && dx == 0 && dy == -1) {
dx = 1;
dy = 0;
left += 1;
}
// 每次按照当前方向前进一格。
System.out.print(matrix[y][x] + " ");
x += dx;
y += dy;
}
}
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
printMatrix(matrix);
}
}