题1:顺时针打印二维数组
-
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
思路: 先设定好边界,行、列,还有初始值。设定好边界后,用while去遍历打印的动作,先右后下再左再上,这个顺时针的动作,因为你会发现其实顺时针的规律也就这样,只要重复循环这个动作即可得出答案。
具体思路:
- 设置好边界初始值
int leftUpRow = 0;
int leftUpCol = 0;
int rightDownRow = matrix.length - 1; //行
int rightDownCol = matrix[0].length - 1; //列
while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol)
//设置边界,且遍历- 后面的步骤其实就是右走、下走、左走、上走,顺时针动作
int r = leftUpRow, c = leftUpCol;
实时更新步骤的初始值- 以c为起点向右边走到边界rightDownCol
while (c <= rightDownCol) {
System.out.print(matrix[r][c++] + " ");
}
- 遍历到 rightDownCol 后
{1, 2, 3, 4 , 100},
{5, 6, 7, 8 , 101},
{9, 10, 11, 12 ,102},
{13, 14, 15, 16 ,103}
public class 顺时针打印二维数组 {
public static void main(String[] args){
int[][] matrix = {
{1, 2, 3, 4 , 100},
{5, 6, 7, 8 , 101},
{9, 10, 11, 12 ,102},
{13, 14, 15, 16 ,103}
};
print(matrix);
}
static void print(int[][] matrix) {
int leftUpRow = 0;
int leftUpCol = 0;
int rightDownRow = matrix.length - 1; //行
int rightDownCol = matrix[0].length - 1; //列
while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol) {
int r = leftUpRow; // 行起步
int c = leftUpCol; // 列起步
//上面一条边
while (c <= rightDownCol) {
System.out.print(matrix[r][c++] + " ");
}
//恢复
c = rightDownCol;
r++;
//右边的一条边
while (r <= rightDownRow) {
System.out.print(matrix[r++][c] + " ");
}
//恢复
r = rightDownRow;
c--;
//下面一条边
while (c >= leftUpCol) {
System.out.print(matrix[r][c--] + " ");
}
//恢复
c = leftUpCol;
r--;
while (r > leftUpRow) {
System.out.print(matrix[r--][c] + " ");
}
leftUpRow++;
leftUpCol++;
rightDownRow--;
rightDownCol--;
}
}
}