package com.xjj.Ah;
import java.util.LinkedList;
/*----深度搜索--水管工游戏----
* 1. remove(),removeFirst():先移除在获取元素
* 2. 利用队列输出
*
* 3.基本模型
* void dfs(int i, int j)
* {
* 判断边界--return
* 尝试每一种可能
* for(int i = 1; i <= n; i++)
* {
* 判断(if)是否越界;
* 判断(if,for)符合要求(未被遍历)
* 继续下一步 dfs(step+1);
* 上一个标记取消
* }
* 返回(return)
* }
* */
public class Ah_4_6 {
static int N = 5, M = 4; //终点
static int[][] a = {{5,3,5,3},{1,5,3,0},{2,3,5,1},{6,1,1,5},{1,5,5,4}};
int[][] book = new int[5][4];
static int flag = 0;
class Dis{
int x = 0;
int y = 0;
}
LinkedList<Dis> list = new LinkedList<>();
//
public void dfs(int i, int j, int dir){
//到达终点
if (i == N-1 && j == M) {
flag = 1;
while(!list.isEmpty()){
//必须先获得在移除
System.out.println("(" + list.getFirst().x + "," +list.getFirst().y + ")");
list.remove();
}
return;
}
//越界
if (i > N-1 || i < 0 || j > M-1 || j < 0) {
return;
}
if (book[i][j] == 1)
return;
book[i][j] = 1;
Dis d = new Dis();
d.x = i;
d.y = j;
list.add(d);
//进水口在左边
if (dir == 1) {
//直管
if (a[i][j] == 5 || a[i][j] == 6) {
dfs(i, j+1, 1);
}
//弯管
if (a[i][j] >= 1 && a[i][j] <=4) {
dfs(i-1, j, 4);
dfs(i+1, j, 2);
}
}
//进水口在上边
if (dir == 2) {
//直管
if (a[i][j] == 5 || a[i][j] == 6) {
dfs(i+1, j, 2);
}
//弯管
if (a[i][j] >= 1 && a[i][j] <=4) {
dfs(i, j-1, 3);
dfs(i, j+1, 1);
}
}
//进水口在右边
if (dir == 3) {
//直管
if (a[i][j] == 5 || a[i][j] == 6) {
dfs(i, j-1, 3);
}
//弯管
if (a[i][j] >= 1 && a[i][j] <=4) {
dfs(i-1, j, 4);
dfs(i+1, j, 2);
}
}
//进水口在下边
if (dir == 4) {
//直管
if (a[i][j] == 5 || a[i][j] == 6) {
dfs(i-1, j, 4);
}
//弯管
if (a[i][j] >= 1 && a[i][j] <=4) {
dfs(i, j-1, 3);
dfs(i, j+1, 1);
}
}
book[i][j] = 0;
if (!list.isEmpty())
list.removeLast();
return;
}
public static void main(String[] args) {
Ah_4_6 ah = new Ah_4_6();
ah.dfs(0, 0, 1);
if (flag == 1) {
System.out.println("找到路径!");
}
else {
System.out.println("不可能!");
}
}
}
深度搜索--水管工游戏
最新推荐文章于 2022-08-14 09:35:25 发布