顺时针从外往里打印数字
顺时针从外往里打印数字
参考链接 https://mp.weixin.qq.com/s/nzUTmCuIaSgtpag5S1RQ3w
/**
* @author lin
* @date 18/7/27
* @license Copyright (c) 2016 那镁克
*/
public class demo {
public void print(int a[][]) {
int realRow = a.length;
int row = realRow / 2;
if ((realRow&1) == 1) {
row = row + 1;
}
for (int r = 0, c = 0; r < row; r ++, c++) {
int col = a[r].length;
int dr = r;
int dc = c;
while (dc < c + col - c * 2) {
System.out.print(a[dr][dc] + " ");
dc ++;
}
dc --;
dr ++;
while (dr < r + realRow - r * 2) {
System.out.print(a[dr][dc] + " ");
dr ++;
}
dr --;
dc --;
while (dc >= c) {
System.out.print(a[dr][dc] + " ");
dc --;
}
dc ++;
dr --;
while (dr > r) {
System.out.print(a[dr][dc] + " ");
dr --;
}
}
}
public static void main(String[] args) {
// int arr[][] = {
// {1,2,3,4,5},
// {14,15,16,17,6},
// {13,20,19,18,7},
// {12,11,10,9,8}
// };
int arr[][] = {
{1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};
demo d = new demo();
d.print(arr);
}
}
思路
int arr[][] = {
{1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};
对应的索引其实就是:
0 [0, 1, 2, 3, 4]
1 [0, , 4]
2 [0, , 4]
3 [0, , 4]
4 [0, 1, 2, 3, 4]
0 [ ]
1 [ , 1, 2, 3, ]
2 [, 1, 2, 3 ]
3 [, 1, 2, 3 ]
4 [ ]
里面相当于又是一个二维数组
这恐怕是最挫的一种写法了
学会勇敢