2023luojie @ 2024-01-25 17:34:06
我想用传说中的“右手原则”过,可是TLE60分。其他的3、4毫秒就过了,但有四个竟然TLE?根据题目,终点不可能在中间,所以应该右手原则能过。不知是右手原则不对,是我代码编错了?
#include <iostream>
#include <vector>
#include <string>
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
bool isValid(int x, int y, int n, int m) {
return x >= 0 && x < n && y >= 0 && y < m;
}
bool solveMaze(std::vector<std::string>& maze, int n, int m) {
int dir = 1;
int x = 0, y = 0;
while (true) {
if (x == n - 1 && y == m - 1) {
return true;
}
int right = (dir + 1) % 4;
int nx = x + dx[right];
int ny = y + dy[right];
if (isValid(nx, ny, n, m) && maze[nx][ny] != '#') {
x = nx;
y = ny;
dir = right;
} else {
nx = x + dx[dir];
ny = y + dy[dir];
if (isValid(nx, ny, n, m) && maze[nx][ny] != '#') {
x = nx;
y = ny;
} else {
dir = (dir + 3) % 4;
}
}
}
return false;
}
int main() {
int n, m;
std::cin >> n >> m;
std::vector<std::string> maze(n);
for (int i = 0; i < n; ++i) {
std::cin >> maze[i];
}
if (solveMaze(maze, n, m)) {
std::cout << "Yes" << std::endl;
} else {
std::cout << "No" << std::endl;
}
return 0;
}
by zgy_123 @ 2024-01-25 17:36:17
int x = 0, y = 0;
起点
@2023luojie
by cff_0102 @ 2024-01-25 17:46:09
@zgy_123 ?
by NaSbO3 @ 2024-01-25 17:48:00
没有记录走过的位置导致陷入死循环TLE
by NaSbO3 @ 2024-01-25 17:49:56
而且不能用右手原则,因为迷宫的路径中存在环路,可能陷入死循环
by cff_0102 @ 2024-01-25 17:50:02
@2023luojie 你试试一个No的情况
by _XHY20180718_ @ 2024-01-25 18:02:08
@NaSbO3
存在环路右手原则不会死循环吧?
除非是 No 的情况。
by Crab_Tang @ 2024-01-25 18:18:32
@XHY20180718 会的,设想一个圈,有出路,但是按照右手原则永远走不到出路。。
by _XHY20180718_ @ 2024-01-25 18:19:00
@Robots75 为什么找不到?
by _XHY20180718_ @ 2024-01-25 18:19:15
肯定可以找到啊?
by 2023luojie @ 2024-01-25 18:39:19
哎呀,我搞错了,找不到出路就会死循环,太尴尬了……