原文是日語,這裏就寫中文了node
Descriptions:ios
在H * W的地圖上有N個奶酪工廠,每一個工廠分別生產硬度爲1-N的奶酪。有一隻老鼠準備從出發點吃遍每個工廠的奶酪。老鼠有一個體力值,初始時爲1,每吃一個工廠的奶酪體力值增長1(每一個工廠只能吃一次),且老鼠只能吃硬度不大於當前體力值的奶酪。 老鼠從當前格到上下左右相鄰的無障礙物的格須要時間1單位,有障礙物的格不能走。走到工廠上時便可吃到該工廠的奶酪,吃奶酪時間不計。問吃遍全部奶酪最少用時spa
input.net
第一行三個整數H(1 <= H <= 1000)、W(1 <= W <=1000)、N(1 <= N <= 9),以後H行W列爲地圖, 「.「爲空地, 」X「爲障礙物,」S「爲老鼠洞,N表示有N個生產奶酪的工廠,硬度爲1-N。code
output blog
吃完全部工廠的最小步數隊列
Sample Input 1ip
3 3 1 S.. ... ..1
Sample Output 1ci
4
Sample Input 2get
4 5 2 .X..1 ....X .XX.S .2.X.
Sample Output 2
12
Sample Input 3
10 10 9 .X...X.S.X 6..5X..X1X ...XXXX..X X..9X...X. 8.X2X..X3X ...XX.X4.. XX....7X.. X..X..XX.. X...X.XX.. ..X.......
Sample Output 3
91
題目連接:
https://vjudge.net/problem/Aizu-0558
題目比較複雜
簡單來講就是讓你求從起點‘S’到‘1’,‘1’到‘2’,‘2’到‘3’...‘n-1’到‘n’的最短距離,這樣你們應該都會了吧,我這裏寫的bfs,具體能夠看註釋,dfs應該也行......
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> #include <sstream> #define mod 1000000007 #define eps 1e-6 #define ll long long #define INF 0x3f3f3f3f #define MEM(x,y) memset(x,y,sizeof(x)) #define Maxn 1005 using namespace std; struct node { int x,y,step;//在(x,y)的步數 }; node now,net; node a[Maxn*Maxn];//工廠 char mp[Maxn][Maxn];//地圖 int vis[Maxn][Maxn];//標記是否走過 int dt[][2] = {{0,1},{1,0},{0,-1},{-1,0}};//4個方向 int h,w,n; int total; int bfs(node s,node e)//從s走到e { MEM(vis,0);//沒次都要初始化爲0 queue<node>q; now.x=s.x,now.y=s.y,now.step=s.step;//初始化隊列 vis[now.x][now.y]=1; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); if(now.x==e.x&&now.y==e.y)//找到目的地 return now.step; for(int i=0; i<4; i++)//四個方向走法 { net.x=now.x+dt[i][0]; net.y=now.y+dt[i][1]; net.step=now.step+1; if(net.x>=0&&net.x<h&&net.y>=0&&net.y<w&&!vis[net.x][net.y]&&mp[net.x][net.y]!='X')//知足條件 { vis[net.x][net.y]=1;//標記走過 q.push(net); } } } } int main() { cin>>h>>w>>n; for(int i=0; i<h; i++) for(int j=0; j<w; j++) { cin>>mp[i][j]; if(mp[i][j]=='S')//把起點設爲0 mp[i][j]='0'; for(int k=0; k<=n; k++)//標記工廠,分別儲存 { if(mp[i][j]-'0'==k) { a[k].x=i; a[k].y=j; a[k].step=0; } } } total=0; for(int i=0; i<n; i++)//開始搜索 增長步數 total+=bfs(a[i],a[i+1]);//a[0]到a[1] a[1]到a[2]...... cout<<total<<endl; }