BFS记录路径第一炮
题目连接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2465
思路:搜索找路径问题,DFS进行,调用 DFS(当前->当前点父节点)->起点,思想,以栈为储存结构,保存路径。
和以往BFS不一样的是地图储存在结构体里。。。注意
在DFS时候,BLF0是当前点的父节点,BLF1是其子节点,因为初始时cost是无限大,每次进出队列的过程都保证当前的cost是较小值,所以DFS方向查找路径储存的花费一定是最优的。
504 KB 0ms
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
const int N = 210;
const int maxn = 110;
const int maxm = 21010;
const int inf = 1e8;
#define MIN INT_MIN
#define MAX 1e6
#define LL long long
#define init(a) memset(a,0,sizeof(a))
#define FOR(i,a,b) for(int i = a;i<b;i++)
#define max(a,b) (a>b)?(a):(b)
#define min(a,b) (a>b)?(b):(a)
using namespace std;
int n,m;
struct node
{
int cost,prex,prey,nowx,nowy;
char fuhao;
}ma[105][105];
int mv[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool OK(int x,int y,int num)
{
//判断当前地图是否是数字
if(((0<=ma[x][y].fuhao-'0') && (ma[x][y].fuhao-'0')<=9)&& ma[x][y].cost>num+ma[x][y].fuhao-'0')
return true ;
return false;
}
bool BFS()
{
queue<node>q;
node t;
int x,y;
ma[0][0].cost=0;
q.push(ma[0][0]);
while(!q.empty())
{
t = q.front();
q.pop();
if(t.nowx == n-1 && t.nowy == m-1)
return true;
FOR(i,0,4)
{
x=t.nowx+mv[i][0];
y=t.nowy+mv[i][1];
if(0<=x && x<n && 0<=y && y<m)
{
if(OK(x,y,t.cost))//判断数
{
ma[x][y].cost = t.cost + ma[x][y].fuhao - '0' + 1;
ma[x][y].prex = t.nowx;
ma[x][y].prey = t.nowy;
q.push(ma[x][y]);
}
else if(ma[x][y].fuhao =='.' && ma[x][y].cost > ma[t.nowx][t.nowy].cost+1)
{
ma[x][y].cost = ma[t.nowx][t.nowy].cost + 1;
ma[x][y].prex = t.nowx;
ma[x][y].prey = t.nowy;
q.push(ma[x][y]);
}
}
}
}
return 0;
}
void LOL(int nowx,int nowy)//DFS找父节点
{
if(nowx==0 && nowy==0)
return ;
LOL(ma[nowx][nowy].prex,ma[nowx][nowy].prey);
int BLF0 = ma[ma[nowx][nowy].prex][ma[nowx][nowy].prey].cost;
BLF0 += 1;
int BLF1 = ma[nowx][nowy].cost;
printf("%ds:(%d,%d)->(%d,%d)\n",BLF0,ma[nowx][nowy].prex,ma[nowx][nowy].prey,nowx,nowy);
BLF0 += 1;
FOR(i,BLF0,BLF1+1)
{
printf("%ds:FIGHT AT (%d,%d)\n",i,nowx,nowy);
}
}
int main()
{
char str[110];
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0 && m==0)
break;
FOR(i,0,n)
{
scanf("%*c%s",str);
FOR(j,0,m)
{
ma[i][j].fuhao = str[j];
ma[i][j].nowx = i;
ma[i][j].nowy = j;
ma[i][j].cost = inf;//BFS记录路径找最小值问题 ,花费初始化一定要最大
}
}
int BLF2 = BFS();
if(!BLF2)
{
puts("GAME OVER.");
puts("FINISH");
continue;
}
LOL(n-1,m-1);
puts("FINISH");
}
return 0;
}