深度优先遍历过程。
从一个点向下试,直到试不下去为止。
图与树不同,树从一个根开始,向下走,一定有走不下去的时候,而图存在环,为此,需要记录每一个点是否被遍历过了,如果被遍历过,在下面的遍历中就不需要走了,当没有相邻节点时,就退回。
假设迷宫有5行4列
二维数组0表示空地 1表示障碍物,入口为0,0
步数最少到达3,2
//深度优先搜索迷宫问题
public class Dfs {
int p;
int q;
int min =Integer.MAX_VALUE;
int m;
int n;
int book[][] = new int [50][50];
int next[][] ={{0,1},{1,0},{0,-1},{-1,0}};
int a[][];
/**
* @return the min
*/
public int getMin() {
return min;
}
/**
* @param min the min to set
*/
public void setMin(int min) {
this.min = min;
}
/**
* @return the p
*/
public int getP() {
return p;
}
/**
* @param p the p to set
*/
public void setP(int p) {
this.p = p;
}
/**
* @return the q
*/
public int getQ() {
return q;
}
/**
* @param q the q to set
*/
public void setQ(int q) {
this.q = q;
}
/**
* @return the m
*/
public int getM() {
return m;
}
/**
* @param m the m to set
*/
public void setM(int m) {
this.m = m;
}
/**
* @return the n
*/
public int getN() {
return n;
}
/**
* @param n the n to set
*/
public void setN(int n) {
this.n = n;
}
/**
* @return the a
*/
public int[][] getA() {
return a;
}
/**
* @param a the a to set
*/
public void setA(int[][] a) {
this.a = a;
}
public void dfs(int x,int y,int step){
int tx;
int ty;
int k;
if(x==p-1&&y==q-1){
if(step<min){
min = step;
setMin(min);
}
return ;
}
for( k=0;k<4;k++){
tx=x+next[k][0];
ty=y+next[k][1];
if(tx>=m||ty>=n||tx<0||ty<0)
{
continue;
}
if(book[x][y]==0&&a[x][y]==0){
book[x][y] =1;
dfs(tx,ty,step+1);
book[x][y] =0;
}
}
return;
}
public static void main(String[] args) {
Dfs dfs = new Dfs();
int a[][]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}};
dfs.setA(a);
dfs.setM(5);
dfs.setN(4);
dfs.setP(4);
dfs.setQ(3);
dfs.dfs(0, 0, 0);
System.out.println(dfs.getMin());
}
}