为什么会错呢?0分求助
查看原帖
为什么会错呢?0分求助
285414
Swiftie_wyc22楼主2021/12/26 21:56

思路:先打表,搜索整个连通块。错应该在搜索里

#include <bits/stdc++.h>

using namespace std;
int n, m;
char c[1001][1001];
int f[1001][1001];
int dirx[] = {1, 0, -1, 0};
int diry[] = {0, 1, 0, -1};
bool vis[1001][1001];
int cnt = 0;

void dfs(int x, int y)
{
    cnt++;
    vis[x][y] = true; // Mark it found
    for (int k = 0; k < 4; k++)
    {
        int dx, dy;
        dx = x + dirx[k];
        dy = y + diry[k];
        if (c[x][y] == '1')
        {
            if (c[dx][dy] == '0' && !vis[dx][dy] && dx >= 0 && dx < n && dy >= 0 && dy < n && f[dx][dy] == 0)
            {
                vis[dx][dy] = true;
                dfs(dx, dy);
                f[dx][dy] = max(f[x][y], cnt);
            }
        }
        else
        {
            if (c[dx][dy] == '1' && !vis[dx][dy] && dx >= 0 && dx < n && dy >= 0 && dy < n && f[dx][dy] == 0)
            {
                vis[dx][dy] = true;
                dfs(dx, dy);
                f[dx][dy] = max(f[x][y], cnt);
            }
        }
    }
    f[x][y] = max(f[x][y], cnt);
}

int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            cin >> c[i][j];

    int sx, sy;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (f[i][j] == 0)
            {
                cnt = 0;
                dfs(i, j);
            }
        }
    }
    
    while (m--)
    {
        cin >> sx >> sy;
        cout << f[sx - 1][sy - 1] << endl;
    }

    return 0;
}
2021/12/26 21:56
加载中...