我打算用 BFS,我 BFS 这块比较弱。但问什么 BFS 分数比 DFS 还低啊!
// Problem:
// P1141 01迷宫
//
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1141
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
int n, m;
char ch[1005][1005];
bool vis[1005][1005];
int nex[4][2] = {
{1, 0},
{0, 1},
{-1, 0},
{0, -1}
};
int ans = 0;
struct point
{
int x;
int y;
};
void bfs(int x, int y)
{
queue<point> q;
q.push(point{x, y});
point data;
while (!q.empty())
{
data = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
if (data.x + nex[i][0] <= n && data.y + nex[i][1] <= n
&& data.x + nex[i][0] >= 1 && data.y + nex[i][1] >= 1)
{
if (ch[data.x][data.y] == '0'
&& ch[data.x + nex[i][0]][data.y + nex[i][1]]
== '1' && !vis[data.x + nex[i][0]][data.y + nex[i][1]])
{
ans++;
q.push(point{
data.x + nex[i][0],
data.y + nex[i][1]
});
vis[data.x + nex[i][0]][data.y + nex[i][1]] = 1;
}
if (ch[data.x][data.y] == '1'
&& ch[data.x + nex[i][0]][data.y + nex[i][1]]
== '0' && !vis[data.x + nex[i][0]][data.y + nex[i][1]])
{
ans++;
q.push(point{
data.x + nex[i][0],
data.y + nex[i][1]
});
vis[data.x + nex[i][0]][data.y + nex[i][1]] = 1;
}
}
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> ch[i][j];
}
}
while (m--)
{
int x, y;
cin >> x >> y;
memset(vis, 0, sizeof(vis));
ans = 0;
bfs(x, y);
cout << ans << endl;
}
}