AcWing 844. Go through the maze(bfs) Described by Java

Classic problem in AcWing
BFS Module.
And write the Queue in array and Pair<Integer, Integer> in Java.
The Code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(System.out);
    int N = 107;
    int n, m;
    int g[][] = new int[N][N], d[][] = new int[N][N];
    PII[] q = new PII[N * N];
    int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};

    public static void main(String[] args) throws IOException {
        Main m = new Main();
    }

    public Main() throws IOException {
        String str1[] = br.readLine().split(" ");
        n = Integer.parseInt(str1[0]);
        m = Integer.parseInt(str1[1]);
        for (int i = 0; i < n; i++) {
            String str2[] = br.readLine().split(" ");
            for (int j = 0; j < m; j++) g[i][j] = Integer.parseInt(str2[j]);
        }
        pw.println(bfs());
        pw.flush();
        br.close();
    }

    public int bfs() {
        int hh = 0, tt = 0;
        q[0] = new PII(0, 0);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                d[i][j] = -1;
        d[0][0] = 0;
        while (hh <= tt) {
            PII t = q[hh++];
            for (int i = 0; i < 4; i++) {
                int x = t.getFirst() + dx[i], y = t.getSecond() + dy[i];
                if (x >= 0 && y >= 0 && x < n && y < m && g[x][y] == 0 && d[x][y] == -1) {
                    d[x][y] = d[t.getFirst()][t.getSecond()] + 1;
                    q[++tt] = new PII(x, y);
                }
            }
        }
        return d[n - 1][m - 1];
    }

}

class PII {
    private int first;
    private int second;

    public PII(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public void setFirst(int first) {
        this.first = first;
    }

    public int getSecond() {
        return second;
    }

    public void setSecond(int second) {
        this.second = second;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值