66tps 01bfs求调,玄关
查看原帖
66tps 01bfs求调,玄关
558202
gogei楼主2024/7/27 22:13
#include <bits/stdc++.h>
using namespace std;
const int N = 500 + 5;
const int dx[] = {1, -1, 1, -1}, dy[] = {1, 1, -1, -1};
struct Node
{
    int x, y;
};
int n, m, dis[N][N];
bool g[N][N][4], vis[N][N];
void bfs()
{
    deque<Node> q;
    memset(dis, 0x3f, sizeof(dis));
    q.push_back({1, 1});
    vis[1][1] = 1;
    dis[1][1] = 0;
    while (!q.empty())
    {
        Node now = q.front();
        q.pop_front();
        int x = now.x, y = now.y;
        if (x == n + 1 && y == m + 1)
        {
            cout << dis[n + 1][m + 1] << endl;
            exit(0);
        }
        for (int i = 0; i < 4; i++)
        {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx < 1 || nx > n + 1 || ny < 1 || ny > m + 1 || vis[nx][ny])
                continue;
            vis[nx][ny] = 1;
            if (g[x][y][i])
            {
                if (dis[nx][ny] > dis[x][y])
                {
                    dis[nx][ny] = dis[x][y];
                    q.push_front({nx, ny});
                }
            }
            else
            {
                if (dis[nx][ny] > dis[x][y] + 1)
                {
                    dis[nx][ny] = dis[x][y] + 1;
                    q.push_back({nx, ny});
                }
            }
        }
    }
}
signed main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            char c;
            cin >> c;
            if (c == '/')
            {
                g[i][j + 1][2] = 1;
                g[i + 1][j][1] = 1;
            }
            else
            {
                g[i][j][0] = 1;
                g[i + 1][j + 1][3] = 1;
            }
        }
    }
    bfs();
    cout << "NO SOLUTION" << endl;
    return 0;
}
2024/7/27 22:13
加载中...