1113. 红与黑

发布时间 2023-11-01 17:59:44作者: Gold_stein

这道题注意要记录的是总步数,而不是当前步数

#include <iostream>
#include <cstring>
using namespace std;
const int N = 105;
char g[N][N];
int k, n;
bool vis[N][N];

int sx, sy, ex, ey;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
void dfs(int x, int y)
{
    vis[x][y] = 1;
    if (x == ex && y == ey) return ;
    for(int i = 0; i < 4; i++)
    {
        int nx = x + dx[i], ny = y + dy[i];
        if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
        if(g[nx][ny] == '#') continue;
        if(vis[nx][ny]) continue;
        dfs(nx, ny);
    }
}
int main()
{
    cin >> k;
    while (k--)
    {
        memset(vis, 0, sizeof vis);
        cin >> n;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                cin >> g[i][j];
            }
        cin >> sx >> sy >> ex >> ey;
        if(g[sx][sy] == '#') 
        {
            puts("NO");
            continue;
        }
        dfs(sx, sy);
        if (vis[ex][ey])
            puts("YES");
        else
            puts("NO");
    }
    return 0;
}

错误示范:

void dfs(int x, int y, int step)
{
    vis[x][y] = 1;
    if (x == ex && y == ey)
    {
        ans = max(ans, step);
        return;
    }
    for(int i = 0; i < 4; i++)
    {
        int nx = x + dx[i], ny = y + dy[i];
        if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
        if(g[nx][ny] == '#') continue;
        if(vis[nx][ny]) continue;
        dfs(nx, ny, step + 1);
    }
}

这样子就只会统计当前点到源点的步数,而不是方块数量