洛谷 P1141 01迷宫 Java

import java.io.*;
import java.util.*;

public class Main {
    static int[] orient = {0, 1, 0, -1, 0};
    static boolean[][] vis;
    public static void main(String[] args) {
        myScanner sc = new myScanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        char[][] x = new char[n][];
        for (int i = 0; i < n; i++) {
            x[i] = sc.next().toCharArray();
        }
        int[][] res = new int[n][n];
        Queue<int[]> queue = new LinkedList<>();
        Queue<int[]> queue2 = new LinkedList<>();
        vis = new boolean[n][n];

        for (int k = 0; k < n; k++) {
            for (int p = 0; p < n; p++) {
                if (!vis[k][p]) {
                    vis[k][p] = true;
                    queue.add(new int[]{k, p});
                    queue2.add(new int[]{k, p});
                    int sum = 0;
                    while (!queue.isEmpty()) {
                        sum++;
                        int[] loc = queue.poll();
                        for (int l = 0; l < 4; l++) {
                            int i = loc[0] + orient[l];
                            int j = loc[1] + orient[l + 1];
                            if (i < 0 || j < 0 || i >= x.length || j >= x.length || vis[i][j] || x[loc[0]][loc[1]] == x[i][j])
                                continue;
                            vis[i][j] = true;
                            queue.offer(new int[]{i, j});
                            queue2.offer(new int[]{i, j});
                        }
                    }
                    while (!queue2.isEmpty()) {
                        int[] loc = queue2.poll();
                        res[loc[0]][loc[1]] = sum;
                    }
                }
            }
        }
        while (m-- > 0) {
            int i = sc.nextInt()-1;
            int j = sc.nextInt()-1;
            System.out.println(res[i][j]);
        }
    }
    
    static class myScanner {
        public BufferedReader reader;
        public StringTokenizer st;

        myScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            st = null;
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值