aoj0558 bfs
2017-10-29 21:19
162 查看
/**
* 在H * W的地图上有N个奶酪工厂,分别生产硬度为1-N的奶酪。
* 有一只吃货老鼠准备从老鼠洞出发吃遍每一个工厂的奶酪。
* 老鼠有一个体力值,初始时为1,每吃一个工厂的奶酪体力值增加1(每个工厂只能吃一次),
* 且老鼠只能吃硬度不大于当前体力值的奶酪。
老鼠从当前格走到相邻的无障碍物的格(上下左右)需要时间1单位,有障碍物的格不能走。
走到工厂上时即可吃到该工厂的奶酪,吃奶酪时间不计。问吃遍所有奶酪最少用时。
*/
* 在H * W的地图上有N个奶酪工厂,分别生产硬度为1-N的奶酪。
* 有一只吃货老鼠准备从老鼠洞出发吃遍每一个工厂的奶酪。
* 老鼠有一个体力值,初始时为1,每吃一个工厂的奶酪体力值增加1(每个工厂只能吃一次),
* 且老鼠只能吃硬度不大于当前体力值的奶酪。
老鼠从当前格走到相邻的无障碍物的格(上下左右)需要时间1单位,有障碍物的格不能走。
走到工厂上时即可吃到该工厂的奶酪,吃奶酪时间不计。问吃遍所有奶酪最少用时。
*/
#include<iostream> #include<queue> using namespace std; typedef struct{ int x; int y; }P;//表示坐标 char graph[1000][1000]; P aim[10]; P s,g;//s起点,g终点 int N,W,H; int vis[1000][1000]; //用来存储距离 int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; int bfs(P s,P g); int main(){ int i,j,t,step=0; cin>>H>>W>>N; for(i=0;i<H;i++) for(j=0;j<W;j++){ cin>>graph[i][j]; if(graph[i][j]<='9'&&graph[i][j]>='1'){ t=graph[i][j]-'0'; aim[t].x=i; aim[t].y=j; } //把1-N的坐标保存在 aim数组中 else if(graph[i][j]=='S'){ s.x=i; s.y=j; graph[i][j]='.'; }//得到最初的起点 } for(i=1;i<=N;i++){ g.x=aim[i].x; g.y=aim[i].y;//1-N ,从小到大,每次把一个 作为终点 step+=bfs(s,g); s.x=g.x; s.y=g.y;//到达这个终点后变终点为起点 graph[g.x][g.y]='.'; } cout<<step<<endl; } int bfs(P s,P g){ queue<P> que; P n; for(int i=0;i<H;i++) for(int j=0;j<W;j++) vis[i][j]=-1; que.push(s); vis[s.x][s.y]=0; while(que.size()){ P p=que.front(); que.pop(); if(p.x==g.x&&p.y==g.y) break; for(int i=0;i<4;i++){ n.x=p.x+dx[i]; n.y=p.y+dy[i];//向四方漫射 if(0<=n.x&&n.x<H&&0<=n.y&&n.y<W&&graph[n.x][n.y]!='X'&&vis[n.x][n.y]==-1){ que.push(n); vis[n.x][n.y]=vis[p.x][p.y]+1; } } } return vis[g.x][g.y]; }
相关文章推荐
- (BFS)aoj0558-Cheese
- ((((((((BFS))))Aoj0558
- AOJ0558——Cheese(BFS)
- AOJ0558(cheese, BFS)
- AOJ0558 Cheese【BFS】
- hdu 2612 Find a way (BFS)
- ZOJ-2365 Strong Defence 贪心,BFS
- BestCoder Round #53 (div.2) HDOJ5423 Rikka with Tree(bfs)
- PAT 1131. Subway Map (30) 地铁换乘,优先BFS搜图应用
- hdu 1067 BFS + hash
- hdu2102 A计划(双层BFS)
- HDOJ 1044 BFS+DFS
- 【图论】bfs树与dfs树的两个妙用
- POJ 3278 Catch That Cow (BFS)
- 寒假集训 最简单的bfs模板题Dungeon Master题解
- hdu 1240 Asteroids! (三维bfs)
- nyoj 353 3D dungeon 【bfs】
- Educational Codeforces Round 37 E. Connected Components?(bfs)
- hdu1429之BFS
- nyoj 635 Oh, my goddess 【bfs(简单题)】