//标题: 振兴中华
// 小明参加了学校的趣味运动会,其中的一个项目是:跳格子。
// 地上画着一些格子,每个格子里写一个字,如下所示:(也可参见p1.jpg)
//从我做起振
//我做起振兴
//做起振兴中
//起振兴中华
// 比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。
// 要求跳过的路线刚好构成“从我做起振兴中华”这句话。
// 请你帮助小明算一算他一共有多少种可能的跳跃路线呢?
public class lanqiao2013_3 {
public static int [][] arr = new int[4][5];
public static int [][] visited = new int[4][5];//0表示未访问 1表示访问过了 因为dfs有回溯的过程
public static int [] flag = new int[8];
public static int count = 0;
//四个方向向量
public static int [][] pos = {{-1,0},{1,0},{0,-1},{0,1}};//上下左右
public static void dfs(int i,int p1,int p2){//从第一个遍历起
if(i==8&&IsTrue()==true){
count++;
return;
}
if(i==8){
return;
}
for(int j=0;j<=3;j++){//向上
if(j==0){
p1 += pos[0][0];
p2 += pos[0][1];
}
if(j==1){ //向下
p1 += pos[1][0];
p2 += pos[1][1];
}
if(j==2){ //向左
p1 += pos[2][0];
p2 += pos[2][1];
}
if(j==3){ //向右
p1 += pos[3][0];
p2 += pos[3][1];
}
if((jugge(p1, p2)==false||visited[p1][p2]==1)){//表示越界 或者已经访问过 无效 退回去
p1 -= pos[j][0];
p2 -= pos[j][1];
}
if((jugge(p1, p2)==true)&&(visited[p1][p2]==0)){//如果未越界 且未访问过
visited[p1][p2]=1; //标记一下
flag[i]=arr[p1][p2];
dfs(i+1,p1,p2);
visited[p1][p2]=0;//记住第一步先退出来
p1 -= pos[j][0];
p2 -= pos[j][1];
}
}
}
public static boolean jugge(int x1,int x2){
if(x1<0||x1>3||x2<0||x2>4){
return false;
}
return true;
}
public static boolean IsTrue(){
for(int i=0;i<flag.length;i++){
if(flag[i]!=i){
return false;
}
}
return true;
}
public static void println(){
System.out.println(Arrays.toString(flag));
}
public static void main(String[] args) {
arr[0] = new int[]{0,1,2,3,4};
arr[1] = new int[]{1,2,3,4,5};
arr[2] = new int[]{2,3,4,5,6};
arr[3] = new int[]{3,4,5,6,7};
visited[0][0]=1;
flag[0]=0;
dfs(1,0,0);
System.out.println("一共有"+" "+count);
}
}
记得每一次退出bfs回到原来的状态
先把标记还原
在还原状态