HDU 1728 - 逃离迷宫

来源:互联网 发布:java edittext获取值 编辑:程序博客网 时间:2024/05/16 03:29

解题思路:在搜索过程中,如果现在扩展的一个节点的转弯次数是n,然后之前这个点的转弯次数是m ,当m>n的时候加入队列

#include <cstdio>#include <cstring>#include <queue>using namespace std;int row, column, k, x1, y1, x2, y2;int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};char maze[2][105][105];struct Node {int x;int y;int change; //从起点到达此结点所需的转弯次数int face;//当前方向};struct Node start;int bfs() {queue<Node> Q;Q.push(start);while (!Q.empty()) {Node root;root = Q.front();Q.pop();for (int i = 0; i < 4; i++) {Node child;child.x = root.x + dir[i][0];child.y = root.y + dir[i][1];if (child.x < 0 || child.x >= column || child.y < 0 || child.y >= row || maze[0][child.y][child.x] == '*')continue; //越界、遇到墙就停止child.change = (root.face != i ? root.change + 1 : root.change); //如果当前方向和之前的方向不同,转弯次数加 1//如果到达此处所需要转弯次数比其他来此处所需要的转弯次数大,就停止。否则记录下到此处所需要的最小转弯次数if (child.change > maze[1][child.y][child.x])continue;maze[1][child.y][child.x] = child.change;child.face = i; //记录下当前的方向if (child.x == x2 - 1 && child.y == y2 - 1) //假如到达终点且所需的转弯次数小于等于最大转弯次数就输出 yesif (child.change <= k + 1 ) {printf("yes\n");return 0;}Q.push(child);}}return 1;}int main() {int t;scanf("%d", &t);while (t--) {memset(maze, 100, sizeof(maze));scanf("%d%d", &row, &column);for (int i = 0; i < row; i++)scanf("%s", maze[0][i]);scanf("%d%d%d%d%d", &k, &x1, &y1, &x2, &y2);start.x = x1 - 1;start.y = y1 - 1;start.change = 0;start.face = 5; if (bfs())printf("no\n");}return 0;}


0 0
原创粉丝点击