P1141 01迷宫 (DFS连通性)

学习blog:https://blog.csdn.net/qq_42780289/article/details/100591825


题解

在一个连通块内,是能保证在连通块上的所有的点能到达这个连通块的任意点的,所以如果一个点已经在一个已经遍历的连通块内的话,就一定是与之前判断连通块内部点的可能性的答案是一致的

Code

// Problem: P1141 01迷宫
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1141
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// Code by: ING__
// 
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define ll long long
#define re return
#define Endl "\n"
#define endl "\n"

using namespace std;

typedef pair<int, int> PII;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};

int n, m;
char mapp[1010][1010];
int vis[1010][1010];
int ans[100010];

void dfs(int x, int y, int num, int i){ // 遍历x, y,当前的数字是num,我们是从i次能遍历到的
	 if(x < 0 || x >= n || y < 0 || y >= n || vis[x][y] != -1 || mapp[x][y] - '0' != num) return;
	 
	 vis[x][y] = i;
	 ans[i]++;
	 
	 for(int j = 0; j < 4; j++){ // 注意变量名!!
	 	dfs(x + dx[j], y + dy[j], !num, i);
	 }
}

int main(){
	cin >> n >> m;
	for(int i = 0; i < n; i++){
		scanf("%s", mapp[i]);
	}
	memset(vis, -1, sizeof(vis));
	for(int i = 1; i <= m; i++){
		int x, y;
		scanf("%d%d", &x, &y);
		x--;
		y--;
		if(vis[x][y] != -1){
			ans[i] = ans[vis[x][y]];
		}
		else{
			dfs(x, y, mapp[x][y] - '0', i);
		}
	}
	
	for(int i = 1; i <= m; i++){
		cout << ans[i] << endl;
	}
	
	re 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值