5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX. 5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX1 5 6 .XX... ..XX1. 2...X. ...XX. XXXXX.
It takes 13 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) FINISH It takes 14 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) 14s:FIGHT AT (4,5) FINISH God please help our poor hero. FINISH
题意:给你一个图,里面由‘.’,‘X’和数字组成,从(0, 0)出发,问能不能到达(n-1, m-1)点。如果能到达, 每走一步,都要花1秒的时间,问最短的时间,并将路径输出来。
这道题题意不难理解,难的是一定要找到最短的那个路径,用一般的BFS肯定wA,不要问我为什么,说多了都是泪~~~
(一般的BFS虽然说能判断能否达到,但不一定是最短距离。)
分析:我们建造一个二维数组,用来记录路径以及从(0, 0)点到达该点的最短距离,每次搜索到一个满足条件的点,都让到该点的时间与原来到达该点的时间相比较,如果是当前的路径小于原来到该点的时间,就更新时间和路径,同时入队列。。最后就是每个点都是最优解了
心得:好题!!!让窝了解了一种如何找最优路径的方法
话说起来,这也是我AC的第一道special judge!!!
代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stack>
#include <queue>
const int M = 105;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1 ,0, 0};
using namespace std;
struct node{
int x, y, prex, prey; //prex,prey是上一个点的坐标
int cost;
}s[M][M];
char map[M][M];
int n, m;
void init(){
int i,j;
for(i = 0; i < M; i ++){
for(j = 0; j < M; j ++)
s[i][j].cost = -1;
}
}
int limit(int x, int y){
return (x>=0&&x<n&&y>=0&&y<m&&map[x][y] != 'X');
}
void out(){ //最后输出的时候用栈来保存路径
printf("It takes %d seconds to reach the target position, let me show you the way.\n", s[n-1][m-1].cost);
stack<node > S;
node a = s[n-1][m-1];
S.push(a);
while(1){
if(a.x == 0&&a.y == 0) break;
a = s[a.prex][a.prey];
S.push(a);
}
a = S.top(); S.pop();
int t = 1;
while(!S.empty()){
node b = S.top(); S.pop();
printf("%ds:(%d,%d)->(%d,%d)\n", t++, a.x, a.y, b.x, b.y);
int temp = b.cost-a.cost-1;
while(temp--){
printf("%ds:FIGHT AT (%d,%d)\n", t++, b.x, b.y);
}
a = b;
}
}
void bfs(){
int i;
node st;
st.x = st.y = st.prex = st.prey = st.cost = 0;
s[0][0] = st;
queue<node >q;
q.push(st);
while(!q.empty()){
node temp = q.front();
q.pop();
for(i = 0; i < 4; i ++){
node cur = temp;
cur.x += dx[i];
cur.y += dy[i];
if(!limit(cur.x, cur.y)) continue;
if(map[cur.x][cur.y] == '.') ++cur.cost;
else cur.cost += (map[cur.x][cur.y]-'0'+1);
if(cur.cost < s[cur.x][cur.y].cost||s[cur.x][cur.y].cost == -1){
s[cur.x][cur.y] = cur;
s[cur.x][cur.y].prex = temp.x; s[cur.x][cur.y].prey = temp.y;
q.push(cur);
}
}
}
if(s[n-1][m-1].cost == -1){
printf("God please help our poor hero.\n"); return;
}
else out();
}
int main(){
while(scanf("%d%d", &n, &m) == 2){
init();
for(int i = 0; i < n; i ++){
scanf("%s", map[i]);
}
bfs();
printf("FINISH\n");
}
return 0;
}
hdoj 1026 Ignatius and the Princess I 【BFS】
原文地址:http://blog.csdn.net/shengweisong/article/details/41546203