跳到正文

个人记录

222

jy_ua约 5 分钟
原文

这是 2026年2月9日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年2月8日
更新
2026年2月12日
篇幅
约 5 分钟

版本

  1. v4当前
  2. v3
  3. v2
  4. v1
C++
// P1363 幻象迷宫
#include <iostream>
#include <queue>
#include <cstring>
#include <cmath>
#define MAXN 1505

using namespace std;

struct Point
{
    int x;
    int y;
    int real_x;
    int real_y;
};

Point p1, p2, p_start;
int n, m;
int mov[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
char c[MAXN][MAXN];
queue<Point> q;
int visited[MAXN][MAXN][2];
bool vis[MAXN][MAXN];

bool bfs()
{
    while(!q.empty())
    {
        p1 = q.front();
        q.pop();

        for (int i = 0; i < 4; i++)
        {
            int nx = (p1.x + mov[i][0] + n) % n;
            int ny = (p1.y + mov[i][1] + m) % m;
            int real_x = p1.real_x + mov[i][0];
            int real_y = p1.real_y + mov[i][1];

            if (c[nx][ny] == '#') continue;
            
            if (!vis[nx][ny])
            {
                vis[nx][ny] = true;
                visited[nx][ny][0] = real_x;
                visited[nx][ny][1] = real_y;

                p2.x = nx;
                p2.y = ny;
                p2.real_x = real_x;
                p2.real_y = real_y;
                q.push(p2);
            }
            else
            {
            	// 回到走过的地方
                if (visited[nx][ny][0] != real_x || visited[nx][ny][1] != real_y)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> n >> m)
    {
	    // 初始化
		memset(visited, 0, sizeof(visited));
    	memset(vis, 0, sizeof(vis));
    	while(!q.empty()) q.pop();
    	memset(c, 0, sizeof(c));
        // 输入
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                cin >> c[i][j];
                if (c[i][j] == 'S')
                {
                    p_start.x = i;
                    p_start.y = j;
				    p_start.real_x = i;
                    p_start.real_y = j;
                }
            }
        }
    	// 起点入队
    	q.push(p_start);
    	vis[p_start.x][p_start.y] = true;
    	visited[p_start.x][p_start.y][0] = p_start.x;
    	visited[p_start.x][p_start.y][1] = p_start.y;
    	// 输出
        bool result = bfs();
        cout << (result ? "Yes" : "No") << endl;
    }
    return 0;
}