走迷宫

给一个 nn 行 mm 列的 22 维的迷宫,'S'表示迷宫额起点,'T'表示迷宫的终点,'#'表示不能通过的点,'.' 表示可以通过的点。你需要从'S'出发走到'T',每次只能上下左右走动,并且只能进入能通过的点,每个点只能通过一次。现在要求你求出有多少种通过迷宫的的方案。

输入格式

第一行输入 nnmm (1 \le n,m \le 10)(1n,m10) 表示迷宫大小

接下来输入 nn 行字符串表示迷宫

输出格式

输入通过迷宫的方法数

样例输入1
2 3
S.#
..T
样例输出1
2
样例输入2
3 3
S..
.#.
..T
样例输出2
2
import java.util.*;
public class Main {
    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) {
        if (mat[x].charAt(y) == 'T') {
			ans++;
			return;
		}

		else if (mat[x].charAt(y) == '#')
			return;

		else {
			vis[x][y] = true;
			for (int i = 0; i < 4; i++) {
				x+=dir[i][0];
				y+=dir[i][1];
				if((-1<x && x<n) && (-1<y && y<m))
					if(vis[x][y]==false){
						dfs(x,y);
					}
				x-=dir[i][0];
				y-=dir[i][1];
			}
			vis[x][y] = false;
		}
    }
    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);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值