bfs广度优先搜索-迷宫问题最优解

输入:
5 6
....S*
.**...
.*..*.
*..**.
.T....
输出:
7
import java.util.*;
// 类 记录当前 坐标x y 步数d 的状态
class Node{
    public int x;
    public int y;
    public int d;

    public Node(int x, int y, int d) {
        this.x = x;
        this.y = y;
        this.d = d;
    }
}

public class LANQIAO1 {
    public static String[] tmp = new String[110];
    public static char[][] maze = new char[110][110];
    public static boolean[][] vis = new boolean[110][110];
    public static int[][] dir = {{-1,0},{0,-1},{1,0},{0,1}};
    public static int n;
    public static int m;
    // 起点
    public static int bfs(int sx,int sy){
        Queue<Node> q = new LinkedList();
        // 把当前位置入队
        q.offer(new Node(sx ,sy ,0));
        // 标记当前位置已被访问
        vis[sx][sy] = true;
        while (!q.isEmpty()){
            // 队列不空则出队队首元素并记录队首元素于now中
            Node now = q.peek();
            q.poll();
            // 将当前位置的四个方向可访问元素入队
            for (int i = 0; i < 4; i++) {
                int tx = now.x + dir[i][0];
                int ty = now.y + dir[i][1];
                // 判断元素是否可以入队
                if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){
                    // 如果找到终点则一层层返回 因为是now的下一层所以返回d+1(比放到最前面少调用一次)
                    if(maze[tx][ty] == 'T'){
                        return now.d + 1;
                    }else { // 没找到终点则新元素入队
                        vis[tx][ty] = true;
                        q.offer(new Node(tx,ty,now.d + 1));
                    }
                }
            }
        }
        // 遍历完所有可访问位置且没有找到T返回
        return -1;
    }
    public static boolean in(int x,int y){
        return x >= 0 && x < n && y >= 0 && y <m;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            tmp[i] = sc.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                maze[i][j] = tmp[i].charAt(j);
            }
        }
        int x = 0,y = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(maze[i][j] == 'S'){
                    x = i;y = j;
                }
            }
        }
        System.out.println(bfs(x, y));

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值