P1141 01迷宫

P1141 01迷宫

思路

连通块,给每个连通块编号。查找时记录结果,若重复查找则直接输出

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	
	static int n,m,num;
	static char[][] map = new char[1005][1005];
	static int[] key = new int[1000005];
	static boolean[][] f = new boolean[1005][1005];
	static int[][] get = new int[1005][1005];
	static int[][] dir = {{0,1},{0,-1},{1,0},{-1, 0}};
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		String[] st = br.readLine().split(" ");
		n = Integer.valueOf(st[0]);
		m = Integer.valueOf(st[1]);
		for(int i=0; i<n; i++) {
			String s = br.readLine();
			map[i] = s.toCharArray();
		}
		
		num = 1;
		
		while(m-- > 0) {
			st = br.readLine().split(" ");
			int x = Integer.valueOf(st[0])-1;
			int y = Integer.valueOf(st[1])-1;
			if(f[x][y] == false) {
				f[x][y] = true;
				key[num] = bfs(x, y);
				num ++;
			}
			System.out.println(key[get[x][y]]);
		}
	}

	private static int bfs(int x, int y) {
		int ans = 1;
		Queue<P> q = new LinkedList<>();
		q.add(new P(x, y));
		get[x][y] = num; 
		f[x][y] = true;
		while(!q.isEmpty()) {
			P p = q.poll();
			for(int i=0; i<4; i++) {
				int u = p.x + dir[i][0];
				int v = p.y + dir[i][1];
				if(check(u, v, map[p.x][p.y]) == false) continue;
				get[u][v] = num; 
				f[u][v] = true;
				q.add(new P(u, v));
				ans ++;
			}
		}
		return ans;
	}
	
	private static boolean check(int u, int v, int k) {
		if(u<0 || u>=n || v<0 || v>=n) return false;
		if((map[u][v]^1) != k)return false;
		if(f[u][v]) return false;
 		return true;
	}

	static class P{
		int x, y;
		public P(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值