深度优先搜索(depth-first-search)简称 dfs,dfs 按照深度优先的方式搜索,通俗的说就是一条路走到黑。dfs 是一种穷举的手段,实际上就是把所有的可行方案列举出来,不断去试探,直到找到问题的解。dfs 是一种搜索算法,dfs 一般的实现方法是借助递归。
dfs的一般写法:
void dfs(int deep) {
if (到达边界) {
// 做一些处理后返回
} else {
for(所有可能的选择) {
dfs(deep + 1);
}
}
}
给一个 n 行 m 列的 2 维的迷宫,'S'表示迷宫额起点,'T'表示迷宫的终点,'#'表示不能通过的点,'.' 表示可以通过的点。你需要从'S'出发走到'T',每次只能上下左右走动,并且只能进入能通过的点,每个点只能通过一次。现在要求你求出有多少种通过迷宫的的方案。
輸入:
第一行输入 nn, m(1≤n,m≤10) 表示迷宫大小
接下来输入 nn 行字符串表示迷宫
输出:通过迷宫的方法
输入:
2 3 S.# ..T输出: 2
输入:
3 3 S.. .#. ..T输出:2
import java.util.*;
public class 走迷宫 {
static String[] mat = new String[11]; // 地图信息
static int ans, n, m; // ans 用来记录最后答案 n, m 表示行列
static int dir[][] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; //对应的上下左右4各方向
static boolean vis[][] = new boolean[11][11];// 用来标记是否访问
static void dfs(int x, int y) {
vis[x][y] = true;//为了标记起点'S'!!!
if (mat[x].charAt(y) == 'T') {
ans++;
return;
}
if (mat[x].charAt(y) == '#') {
return;
}
for (int i = 0; i < dir.length; i++) {
x = x + dir[i][0];
y = y + dir[i][1];
if ((-1 < x && x < n) && (-1 < y && y < m)) {//判断是否越界
if (vis[x][y] == false) {//如果没有访问过
vis[x][y] = true;
dfs(x, y);//搜索
vis[x][y] = false;//回溯
}
}
x = x - dir[i][0];
y = y - dir[i][1];
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
m = cin.nextInt();
for (int i = 0; i < n; ++i) {
mat[i] = cin.next();
}
int x = 0, y = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (mat[i].charAt(j) == 'S') {
x = i;
y = j;
}
}
}
ans = 0;
dfs(x, y);
System.out.println(ans);
}
}