一、判断是否可达
public class DFS判断是否可达 {
static char[][] map={{'S','.','*','.'},{'.','.','.','.'},{'*','*','*','T'}};
static int[][] vis=new int[1000][1000];
static int n=map.length; //行
static int m=map[0].length;//列
static int[][] dist= {{0,-1},{0,1},{-1,0},{1,0}};
static int ans=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
dfs(0,0);
}
static void dfs(int x,int y){
if(map[x][y]=='T') {
System.out.println("sucess");
return;
}
for(int i=0;i<4;i++) {
int xx=x+dist[i][0];
int yy=y+dist[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0&&(map[xx][yy]=='.'||map[xx][yy]=='T')) {
vis[x][y]=1;
dfs(xx,yy);
//vis[x][y]=0;
}
}
//
}
}
二、输出所有路径
用stack存储
import java.util.Deque;
import java.util.LinkedList;
public class DFS输出路径 {
static char[][] map={{'S','.','.','.'},
{'.','.','.','.'},
{'*','*','*','T'}};
static int[][] vis=new int[1000][1000];
static int n=map.length; //行
static int m=map[0].length;//列
static int[][] dist= {{0,-1},{0,1},{-1,0},{1,0}};
static int ans=0;
static Deque<Node> stack=new LinkedList<>();
public static void main(String[] args) {
// TODO Auto-generated method stub
dfs(0,0,0);
}
static class Node{
private int x;
private int y;
private int step;
public Node(int x, int y, int step) {
super();
this.x = x;
this.y = y;
this.step = step;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
}
static void dfs(int x,int y,int step){
if(map[x][y]=='T') {
for(Node node:stack) {
System.out.println("("+node.getX()+","+node.getY()+")"+" "+node.getStep());
}
System.out.println();
return;
}
for(int i=0;i<4;i++) {
int xx=x+dist[i][0];
int yy=y+dist[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0&&(map[xx][yy]=='.'||map[xx][yy]=='T')) {
vis[x][y]=1;
stack.offer(new Node(x,y,step+1));
dfs(xx,yy,step+1);
vis[x][y]=0;
stack.pollLast();
}
}
//
}
}