洛谷P1141 01迷宫

我们可以使用dfs,走格查找 

#include <bits/stdc++.h>

using namespace std;

int n, m, x, y, ct;
char c;
int a[1009][1009];
int vis[1009][1009];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

void f (int x, int y) {
	vis[x][y] = false;
	int nx, ny;
	for (int i = 0; i < 4; i++) {
		nx = dx[i] + x;
		ny = dy[i] + y;
		if (nx < 1 || nx > n || ny < 1 || ny > n || a[nx][ny] == a[x][y] || !(vis[nx][ny])) continue;
		ct++;
		f (nx, ny);
		vis[nx][ny] = false;
	}
	return;
}

int main () {
	
	cin >> n >> m;
	
	for (int i = 1; i <= n; i++)
		for (int k = 1; k <= n; k++) {
			cin >> c;
			a[i][k] = c - '0';
		}
	
	for (int i = 1; i <= m; i++) {
		memset (vis, true, sizeof (vis));
		cin >> x >> y;
		vis[x][y] = false;
		ct = 1;
		f (x, y);
		cout << ct << endl;
	}
	
	return 0;
}

结果发现60分,TLE

因为dfs需要递归,

太慢了

所以使用bfs

bfs使用queue代替了慢慢的递归

#include <bits/stdc++.h>

using namespace std;

char c;
int n, m, nextColor;
int a[1009][1009], vis[1009][1009], colorCount[1000009];
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};

int bfs (int x, int y) {
	if (vis[x][y] != -1)
		return colorCount[vis[x][y]];
	int cnt = 1;
	queue<int> q;
	vis[x][y] = nextColor; q.push(x); q.push(y);
	while (!q.empty()) {
		x = q.front(); q.pop(); y = q.front(); q.pop();
		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i], ny = y + dy[i];
			if (nx < 1 || nx > n || ny < 1 || ny > n) continue;
			if (vis[nx][ny] == -1 && a[nx][ny] != a[x][y]) {
				vis[nx][ny] = nextColor; cnt++;
				q.push(nx); q.push(ny);
			}
		}
	}
	colorCount[nextColor] = cnt; nextColor++;
	return cnt;
}

int main () {
	
	cin >> n >> m;
	
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			cin >> c;
			a[i][j] = c - '0';
		}
	
	nextColor = 0;
	memset (vis, -1, sizeof(vis));
	
	while (m--) {
		int x, y; cin >> x >> y;
		cout << bfs(x, y) << endl;
	}
	
	return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值