hdu 1026 Ignatius and the Princess I

来源:互联网 发布:aes算法密钥最小长度 编辑:程序博客网 时间:2024/06/10 21:50

        hdu 1026 Ignatius and the Princess I

        题目要求的是从(0, 0)到(n-1, m-1)的最小秒数啦, 首先想到的就是广搜啦, 这道题要求输出搜索过的路径哦, 那么就需要一个额外的数组来记录了.

        用turn[][]数组来记录每次转过的方向, 一次广搜结束后, 然后再从终点顺着走回来, 就可完成路径的记录啦.


#include <stdio.h>#include <string.h>#include <queue>using namespace std;#define MAX 101#define INF 0xfffffffstruct cell {    int x, y;    int step;    friend bool operator<(cell a, cell b) {        return a.step > b.step;    }};int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};char map[MAX][MAX];bool visited[MAX][MAX];int turn[MAX][MAX]; // 记录每次转向cell start, end, go, to;int n, m;int result;int bfs() {    int i;    int ans = INF;    priority_queue<cell> Q;    memset(visited, false, sizeof(visited));    memset(turn, 0, sizeof(turn));    start.x = 0, start.y = 0, start.step = 0;    end.x = n - 1, end.y = m - 1;    Q.push(start);    visited[start.x][start.y] = true;    while (!Q.empty()) {        go = Q.top();        Q.pop();        if (go.x == end.x && go.y == end.y) {            ans = go.step;            return ans;        }        for (i = 0; i < 4; i++) {            to.x = go.x + dir[i][0];            to.y = go.y + dir[i][1];            to.step = go.step + 1;            if (to.x >= 0 && to.x < n && to.y >= 0 && to.y < m                && map[to.x][to.y] != 'X' && !visited[to.x][to.y]) {                if (map[to.x][to.y] >= '1' && map[to.x][to.y] <= '9') {                    to.step += map[to.x][to.y] - '0';                }                visited[to.x][to.y] = true;                turn[to.x][to.y] = i;                Q.push(to);            }        }    }    return  ans;}int printPath(int x,int y) {    int step, i;    if(x == 0 && y == 0) {        step = 1;        printf("%ds:(%d,%d)->", step, x, y);        return step;    }    i = turn[x][y];    step = printPath(x - dir[i][0], y - dir[i][1]);    printf("(%d,%d)\n", x, y);    if(map[x][y] >= '1' && map[x][y] <= '9') {        int s;        s = map[x][y] - '0';        while(s--) {            ++step;            printf("%ds:FIGHT AT (%d,%d)\n", step, x, y);        }    }    //     if(step == result)        return 0;    printf("%ds:(%d,%d)->", ++step, x, y);    return step;}int main() {    int i;    while (scanf("%d%d", &n, &m) == 2) {        memset(map, 0, sizeof(map));        for (i = 0; i < n; i++) {            scanf("%s", map[i]);        }        result = bfs();        if (result == INF) {            printf("God please help our poor hero.\nFINISH\n");        } else {            printf("It takes %d seconds to reach the target position, let me show you the way.\n", result);            printPath(n - 1, m - 1);            printf("FINISH\n");        }    }    return 0;}


原创粉丝点击