DFS求联通块的问题

洛谷[https://www.luogu.org/problemnew/show/P1141]
用广度优先搜索会超时两个数据点

//还是会超时,欸,还得优化 
#include <bits/stdc++.h>
using namespace std;
#define MAX 1005

struct node{
	int x, y;
}s, e;

int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char A[MAX][MAX];
int B[MAX][MAX];
bool visited[MAX][MAX] = {0};	//总的棋盘

queue<struct node> Q;

int BFS(int x, int y, int n) {

	if(visited[x][y]) 
		return B[x][y];
	
	while(!Q.empty()) Q.pop();
	
	int ct = 0, i, j;
	bool v[MAX][MAX] = {0};
	s.x = x;
	s.y = y;
	Q.push(s);
	visited[s.x][s.y] = 1;
	v[s.x][s.y] = 1; 
	ct++;
	
	while(!Q.empty()) {
		s = Q.front();
		Q.pop();
		
		for(int i = 0; i < 4; i++) {
			e.x = s.x + dir[i][0];
			e.y = s.y + dir[i][1];
			if(v[e.x][e.y] || e.x < 0 || e.y < 0 || e.x >= n || e.y >= n) continue;
		
			if(A[s.x][s.y] == '0') {
				if(A[e.x][e.y] == '1'){
					visited[e.x][e.y] = 1;
					v[e.x][e.y] = 1;
					Q.push(e);
					ct++;
				}		
			}
			else {
				if(A[e.x][e.y] == '0') {
					visited[e.x][e.y] = 1;
					v[e.x][e.y] = 1;
					Q.push(e);
					ct++;
				}
			}
		}
	}
	for(i = 0; i < n; i++) {
		for(j = 0; j < n; j++) {
			if(v[i][j])
				B[i][j] = ct;
		}
	}
	return ct;
}

int main() {
	int n, m, i, ct, x, y;
	scanf("%d%d", &n, &m);
	getchar();
	for(i = 0; i < n; i++) {
		scanf("%s", A[i]);
	}
	memset(B, -1, sizeof(B));
	for(i = 0; i < m; i++) {
		scanf("%d%d", &x, &y);
		ct = BFS(x-1, y-1, n);
		printf("%d\n", ct);
	}
	return 0;
}

换成深度优先搜索,求联通块

//求联通块的问题 ,用DFS试一下 
#include <bits/stdc++.h>
using namespace std;
#define MAX 1005

int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char A[MAX][MAX];
int B[MAX][MAX];
int xy[1000005][2];
bool v[MAX][MAX] = {0};	//总的棋盘
int n, ct;

void DFS(int x, int y) {
	int nx, ny;
	xy[ct][0] = x;
	xy[ct][1] = y;
	ct++;
	v[x][y] = 1;
	for(int i = 0; i < 4; i++) {
		nx = x + dir[i][0];
		ny = y + dir[i][1];
		if(nx < 0 || ny < 0 || nx >= n || ny >= n || v[nx][ny]) 
			continue;
		if(A[x][y] != A[nx][ny])
			DFS(x+dir[i][0], y+dir[i][1]);
	}
}

int main() {
	int m, i, x, y, j;
	scanf("%d%d", &n, &m);
	getchar();
	for(i = 0; i < n; i++) {
		scanf("%s", A[i]);
	}

	for(i = 0; i < n; i++) {
		for(j = 0; j < n; j++) {
			if(!v[i][j]) {
				ct = 0;
				DFS(i, j);
				for(int k = 0; k < ct; k++) B[xy[k][0]][xy[k][1]] = ct;
			}
		}
	}
	
	for(i = 0; i < m; i++) {
		scanf("%d%d", &x, &y);
		printf("%d\n", B[x-1][y-1]);
	}
	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值