小菜鸡想用“右手原则”做
查看原帖
小菜鸡想用“右手原则”做
1070310
2023luojie楼主2024/1/25 17:34

我想用传说中的“右手原则”过,可是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;
}
2024/1/25 17:34
加载中...