bys222 @ 2024-12-16 18:45:27
#include <bits/stdc++.h>
using namespace std;
int n, m, dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, ans[1010], cnt, t[1010][1010];
char c[1010][1010];
void dfs(int x, int y)
{
ans[cnt]++;
t[x][y] = cnt;
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < n && t[tx][ty] == 0 && c[x][y] != c[tx][ty]) dfs(tx, ty);
}
}
int main ()
{
freopen("1141.in", "r", stdin);
freopen("1141.out", "w", stdout);
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> c[i];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!t[i][j])
{
cnt++;
dfs(i, j);
}
}
}
while (m--)
{
int x, y;
cin >> x >> y;
x--;
y--;
cout << ans[t[x][y]] << endl;
}
return 0;
}
by jianghaochen117 @ 2024-12-16 18:56:32
在洛谷上提交的代码应去掉freopen
by bys222 @ 2024-12-16 19:28:53
我去掉后交的,去掉后还爆零。
#include <bits/stdc++.h>
using namespace std;
int n, m, dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, ans[1010], cnt, t[1010][1010];
char c[1010][1010];
void dfs(int x, int y)
{
ans[cnt]++;
t[x][y] = cnt;
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < n && t[tx][ty] == 0 && c[x][y] != c[tx][ty]) dfs(tx, ty);
}
}
int main ()
{
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> c[i];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!t[i][j])
{
cnt++;
dfs(i, j);
}
}
}
while (m--)
{
int x, y;
cin >> x >> y;
x--;
y--;
cout << ans[t[x][y]] << endl;
}
return 0;
}