hdoj 1026 搜索

题目链接


#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

const int INF = 9999999;
const int MAX = 102;

struct Node{
	int x, y;
	int step;
	int prex, prey;
	char c;
};
struct cmp{
	bool operator () (const Node &a, const Node &b){
		return a.step > b.step;
	}
};
Node map[MAX][MAX];
int n, m;
int flag;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; 
priority_queue<Node, vector<Node>,cmp> pq;//忘记声明变量了 
int sec;
int bfs()
	{
		Node node;
		while(!pq.empty())//清空内存
		pq.pop();
		map[0][0].step = 0;//开始的step为0 
		pq.push(map[0][0]);
		while(!pq.empty()){
			node = pq.top();
			pq.pop();
			if(node.x == n-1 && node.y == m-1){
				flag = 1;
				return node.step; 
			}
			for(int i = 0; i < 4; i++ ){
				int nx = node.x + dir[i][0];
				int ny = node.y + dir[i][1];
				if(nx < 0 || nx >= n || ny < 0 || ny >= m || map[nx][ny].c =='X') continue;

				if(map[nx][ny].c == '.' && map[nx][ny].step > node.step+1){
					map[nx][ny].step = node.step + 1;
					map[nx][ny].prex = node.x;
					map[nx][ny].prey = node.y;
					pq.push(map[nx][ny]);
				}
				else if(map[nx][ny].c >='1'&&map[nx][ny].c <='9' && map[nx][ny].step > node.step+map[nx][ny].c-'0'+1){
					map[nx][ny].step = node.step + map[nx][ny].c-'0' + 1;
					map[nx][ny].prex = node.x;
					map[nx][ny].prey = node.y;
					pq.push(map[nx][ny]);
				}
			}
			
			
		}
		
		return -1;	
	}
void printPath(int x, int y)
	{ 	
		if(x == 0 && y == 0)
			return ;
		printPath(map[x][y].prex,map[x][y].prey);
		printf("%ds:(%d,%d)->(%d,%d)\n",sec++,map[x][y].prex,map[x][y].prey,x,y);
		if(map[x][y].c >= '1' && map[x][y].c <= '9'){
			int t = map[x][y].c-'0';
			while(t--){
				printf("%ds:FIGHT AT (%d,%d)\n",sec++,x,y);
			}
		}
	}	

int main()
	{
		while(scanf("%d%d",&n,&m) != EOF){
			int i;
		//	getchar();
			for(i = 0; i < n; ++i ){
				getchar();//每行末尾都有 换行符 
				for(int j = 0; j < m; ++j){
					map[i][j].c = getchar();
					map[i][j].x = i;
					map[i][j].y = j;
					map[i][j].step = INF;//step无穷大 代替了 vis
				}
			}
//			for(int i = 0; i < n; i++ ){
//				for(int j = 0; j < m; ++j){
//					cout <<map[i][j].c <<"";
//				}
//				cout <<endl;
//			}
//			
			flag = 0;
			sec = 1;
			int s = bfs();
			if(flag == 0){
				cout << "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",s);
				printPath(n-1,m-1);
				cout<<"FINISH\n";
			} 
		}
		
		return 0;
	}
	
	
		

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值