洛谷__P1363 幻象迷宫
题目链接:P1363 幻象迷宫 - 洛谷
题目大意:
这个迷宫是无限大的,但它是由一个给定的 N×M 的矩阵重复铺展而成的。
具体来说:
-
给定一个 N×M 的矩阵,里面有:
-
.表示道路 -
#表示墙 -
S表示起点(也是道路)
-
-
移动规则:可以上下左右走到相邻的非墙格子。
-
目标:判断能否从起点 走到距离起点无限远的地方(即能否“走出迷宫”)。
思路:
把原来的矩阵边长扩充到2倍
从S点开始洪水填充
如果在洪水的过程中填充到了一个不在原来矩阵的点且这个点在4个子矩阵中任一矩阵的对应点已经被洪水填充过了的话 返回YES
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;
const int N = 3008, mod = 998244353;
int n, m;
int e[N][N];
int sx, sy;
bool ok;
void dfs(int x, int y) {
if (ok) return;
if (x >= n || y >= m) {
if (e[x % n][y % m] == 2 || e[x % n + n][y % m] == 2 || e[x % n][y % m + m] == 2 || e[x % n + n][y % m + m] == 2) {
ok = true;
return;
}
}
e[x][y] = 2;
if (e[(x + 1 + 2 * n) % (2 * n)][y] == 0) dfs((x + 1 + 2 * n) % (2 * n), y) ;
if (e[(x - 1 + 2 * n) % (2 * n)][y] == 0) dfs((x - 1 + 2 * n) % (2 * n), y) ;
if (e[x][(y + 1 + 2 * m) % (2 * m)] == 0) dfs(x, (y + 1 + 2 * m) % (2 * m)) ;
if (e[x][(y - 1 + 2 * m) % (2 * m)] == 0) dfs(x, (y - 1 + 2 * m) % (2 * m)) ;
}
void solve() {
while (cin >> n >> m) {
mst(e, 0);
ok = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c;
cin >> c;
if (c == '#') e[i][j] = 1;
if (c == 'S') sx = i, sy = j;
}
}
for (int i = 0; i < n; i++) {
for (int j = m; j < 2 * m; j++) {
e[i][j] = e[i][j - m];
}
}
for (int i = n; i < 2 * n; i++) {
for (int j = 0; j < 2 * m; j++) {
e[i][j] = e[i - n][j];
}
}
dfs(sx, sy);
if (ok) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号