之前在面试的时候遇到过这样一个题目:
观察下列数字规律,并将其打印在控制台
3 2 9
4 1 8
5 6 7
13 12 11 10 25
14 03 02 09 24
15 04 01 08 23
16 05 06 07 22
17 18 19 20 21
..........
解题思路:
(1)每个矩阵看成一圈,一圈一圈循环赋值
(2)一圈赋值完成之后,控制向外扩张一圈,就可以实现这个算法了
说明:下面是我加以改进过的算法,实现的任意方向的旋转(顺时针逆时针旋转,上下左右控制初始旋转方向(总共8中构建方法))
package util;
import java.util.regex.Pattern;
public class HuiXuanJuZheng {
private int [][] matrix;
private int x ;
private int y;
private String rotateDirection;
private String direction;
private String directionInit;
private int layer;
/**
*
* @param 圈数
* @param CCK|CK,逆时针|顺时针
* @param up|down|left|right,初次旋转方向 上下左右
*/
public HuiXuanJuZheng(int layer,String rotateDirection, String directionInit) {
if (Pattern.matches("CCK|CK",rotateDirection)&&Pattern.matches("up|down|left|right",directionInit)) {
this.matrix = new int[2*layer-1][2*layer-1];
this.x=layer-1;
this.y=layer-1;
this.rotateDirection=rotateDirection;
this.direction=directionInit;
this.directionInit=directionInit;
this.layer=layer;
constructMatrix();
}else {
matrix = null;
}
}
public void constructMatrix(){
/*当前圈数*/
int currentLayer=1;
/*赋值次数*/
int time=1;
String[] flag ={"up","right","down","left"};
if (rotateDirection == "CCK") {
String[]flagC = {"down","right","up","left"};
flag=flagC;
}
/*遍历赋值*/
for (int i = 1; i <= Math.pow(2*layer-1, 2); i++) {
matrix[x][y] = i;
boolean fla=false;
if (Math.pow(2*currentLayer-1,2) == i) {
currentLayer ++;
xy(directionInit);
time=1;
fla=true;
}else{
xy(null);
}
time++;
if (rotateDirection == "CCK") {
switch (direction) {
case "down":
if ((2*currentLayer-2) == time) {
direction = flag[1];
time=0;
}
break;
case "right":
if ((2*currentLayer-2) == time) {
direction = flag[2];
time=0;
}
break;
case "up":
if ((2*currentLayer-2) == time) {
direction = flag[3];
time=0;
}
break;
case "left":
if ((2*currentLayer-2) == time) {
direction = flag[0];
time=0;
}
break;
}
}else {
switch (direction) {
case "up":
if ((2*currentLayer-2) == time) {
direction = flag[1];
time=0;
}
break;
case "right":
if ((2*currentLayer-2) == time) {
direction = flag[2];
time=0;
}
break;
case "down":
if ((2*currentLayer-2) == time) {
direction = flag[3];
time=0;
}
break;
case "left":
if ((2*currentLayer-2) == time) {
direction = flag[0];
time=0;
}
break;
}
}
if (fla) {
time=1;
fla=false;
}
}
}
private void xy(String directionInit) {
String flay=directionInit!=null?directionInit:direction;
switch (flay) {
case "up":
x--;
break;
case "down":
x++;
break;
case "left":
y--;
break;
case "right":
y++;
break;
}
}
public int[][] getSwingMatrix(){
return this.matrix;
}
public static void main(String[] args) {
int [][] mam =new HuiXuanJuZheng(4, "CCK", "up").getSwingMatrix();
for (int[] is : mam) {
for (int i : is) {
if (i<100) {
System.out.print(i<10?"0"+i+" ":i+" ");
}else {
System.out.print(i+" ");
}
}
System.out.println();
}
System.out.println();
}
}