AcWing 1101. 献给阿尔吉侬的花束(bfs)

标准的bfs,不过和花束一点关系都没有…

Problem

bfs模板,再复习一遍

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 210, T, n, m;
    static int dist[][] = new int[N][N];
    static char g[][] = new char[N][N];
    static int dx[] = new int[]{0, 1, 0, -1};
    static int dy[] = new int[]{1, 0, -1, 0};

    public static void main(String[] args) throws IOException {
        T = Integer.parseInt(br.readLine());
        String s[];
        while (T-- > 0) {
            s = br.readLine().split(" ");
            n = Integer.parseInt(s[0]);
            m = Integer.parseInt(s[1]);
            for (int i = 0; i < n; i++) {
                String ss = br.readLine();
                for (int j = 0; j < m; j++) {
                    g[i][j] = ss.charAt(j);
                }
            }

            Pair start = new Pair(-1, -1), end = new Pair(-1, -1);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (g[i][j] == 'E') end = new Pair(i, j);
                    else if (g[i][j] == 'S') start = new Pair(i, j);
                }
            }

            int res = bfs(start, end);
            if (res != -1) pw.println(res);
            else pw.println("oop!");

        }
        pw.flush();
        pw.close();
        br.close();
    }

    public static int bfs(Pair start, Pair end) {
        Queue<Pair> q = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                dist[i][j] = -1;
        }

        dist[start.x][start.y] = 0;
        q.offer(start);

        while (!q.isEmpty()) {
            Pair temp = q.poll();
            for (int i = 0; i < 4; i++) {
                int x = temp.x + dx[i];
                int y = temp.y + dy[i];
                if (x < 0 || x >= n || y < 0 || y >= m) continue;
                if (g[x][y] == '#') continue;
                if (dist[x][y] != -1) continue;

                dist[x][y] = dist[temp.x][temp.y] + 1;

                if (x == end.x && y == end.y) return dist[x][y];
                q.offer(new Pair(x, y));
            }
        }
        return -1;
    }
}

class Pair {
    public int x, y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值