晚上的时候, 有个群友群里忽然问
这个怎么实现的?
我当时随意想了一下,这就是5×5旋转矩阵嘛,遇到5就向下,还没继续往下想,就忽然发现自己的思路不正确…
仔细思考了一下,感觉比较简单靠谱的实现,是先弄个2维数组,向里面填值,再打印;
看起来很简单的一个问题,用了大约半小时写出来了这里分享一下
先看结果,这个是5×5的
下面是代码
/**
*
* @Description
* @qq 59663479
* @E-mail 59663479@qq.com
* @Date 2019年9月3日 下午10:52:01
*/
public class ZhuanQuan {
/*- 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
*/
public static void main(String[] args) {
// 我们只想输入一个数字就看到结果,就把下面的方法 分了层
whirl(5);
}
/**
* 这里做一个中转
* @Description
* @Date 2019年9月3日 下午10:52:08
* @param index
*/
public static void whirl(int index) {
int[][] map = new int[index][index];
// 从第1步,下标 0 , 0 的位置开始走,4表示开始向右走;
whirlImpl(1, 0, 0, map, 4);
for (int i = 0; i < index; i++) {
for (int j = 0; j < index; j++) {
System.out.print(map[i][j] + "\t");
}
System.out.println();
System.out.println();
}
}
/**
*
* @Description
* @Date 2019年9月3日 下午10:52:42
* @param step
* 要走第几步,也就是该在 二维数组中写几了
* @param X
* map的横轴
* @param Y
* map的竖轴
* @param map
* 二维数组
* @param dir
* 1上,2下,3左,4右
*/
public static void whirlImpl(int step, int X, int Y, int[][] map, int dir) {
map[X][Y] = step++;
if (step > map.length * map.length) {
return;
}
if (dir == 4) {
if (Y != map.length - 1 && map[X][Y + 1] == 0) {// 右边能否走通
whirlImpl(step, X, Y + 1, map, dir);
} else if (X != map.length - 1 && map[X + 1][Y] == 0) { // 下面能否走通
whirlImpl(step, X + 1, Y, map, 2);
}
} else if (dir == 2) {
if (X != map.length - 1 && map[X + 1][Y] == 0) {// 下边能否走通
whirlImpl(step, X + 1, Y, map, dir);
} else if (Y != 0 && map[X][Y - 1] == 0) { // 左面能否走通
whirlImpl(step, X, Y - 1, map, 3);
}
} else if (dir == 3) {
if (Y != 0 && map[X][Y - 1] == 0) {// 左边能否走通
whirlImpl(step, X, Y - 1, map, dir);
} else if (X != 0 && map[X - 1][Y] == 0) { // 上面能否走通
whirlImpl(step, X - 1, Y, map, 1);
}
} else if (dir == 1) {
if (X != 0 && map[X - 1][Y] == 0) {// 上边能否走通
whirlImpl(step, X - 1, Y, map, dir);
} else if (Y != map.length - 1 && map[X][Y + 1] == 0) { // 右面能否走通
whirlImpl(step, X, Y + 1, map, 4);
}
}
}
}
也没看别人怎么写的,也不知道自己写的好不好…先放着吧