這個鎮上,有N個奶酪廠,每一個廠都只生產一種奶酪。奶酪的硬度因工廠而異,硬度從1到N的奶酪生產廠家正好各有一個。ios
老鼠的第一個體力是一個,每吃一個奶酪就增長一個體力。不過,老鼠吃不到比本身體力還硬的奶酪。數組
老鼠,一分鐘就能移動到東西南北相鄰的地段,不過不可能進入障礙物區。奶酪工廠不吃奶酪也能路過。寫一個尋找最短期吃完全部奶酪的程序。不過,老鼠吃奶酪的時間是能夠忽視的。spa
輸入爲H+1行。第一行中3個整數H, W, N(1≤H≤1000,1≤W≤1000,1≤N≤9)按照這個順序被寫在上面。從第2行到第H+1行的各行爲,'S', '1', '2',……寫有由'9'、'X'、'.'構成的W字符的字符串,各個寫部分表示各個劃分的狀態。北起i第二,從西j號的區劃(i, j)和記述決定(1那些i那些h, 1那些j那些w),第i + 1行j號的文字,區劃(i, j)若是窩' s ',障礙物時是' x ',若是是空地' . ' ',硬度1,2,…9是生產奶酪的工廠,分別爲'1','2',……成爲'9'。輸入與巢和硬度1,2,……N奶酪生產廠各有一個。其餘格子能夠保證是障礙物或空地。老鼠能夠吃到全部的奶酪。.net
在吃完全部奶酪以前,要輸出表示最短期(分鐘)的整數。翻譯
ps:題面翻譯爲有道翻譯。。。code
思路:題目意思就是讓你求從起點‘S’到‘1’,‘1’到‘2’,‘2’到‘3’...‘n-1’到‘n’的最短距離,我這裏寫的bfs,具體能夠看註釋,dfs應該也行......blog
1 #include<iostream>
2 #include<cstring>
3 #include<cstdio>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 #include<queue>
10 using namespace std; 11 #define ll long long
12 const int mod=1e9+7; 13 const int inf=1e9+7; 14
15 const int maxn=1e3+5; 16
17 char e[maxn][maxn];//存地圖
18
19 bool book[maxn][maxn];//標記是否走過,注意每次bfs裏面都要從新初始化
20
21 int h,w,n; 22
23 int startx,starty;//地點,注意每次bfs的起點不一樣, 24 //此次bfs的終點要被記錄爲下次bfs的起點
25 void init()//初始化
26 { 27 for(int i=1;i<=h;i++) 28 { 29 for(int j=1;j<=w;j++) 30 { 31 book[i][j]=0; 32 } 33 } 34 } 35
36 typedef struct//定義一個結構體存座標以及步數
37 { 38 int x;//座標
39 int y; 40 int f;//步數
41 }St; 42
43 int nextt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//方向數組
44
45 int bfs(char endd) 46 { 47 init();//初始化
48
49 queue<St>q;//建一個隊列,bfs所需
50
51 book[startx][starty]=1;//標記起點爲走過
52 q.push({startx,starty,0});//導入隊列
53
54 int tx,ty,tf; 55 St now; 56
57 while(!q.empty()) 58 { 59 now=q.front();//取出隊首
60
61 for(int i=0;i<4;i++) 62 { 63 tx=now.x+nextt[i][0]; 64 ty=now.y+nextt[i][1]; 65 tf=now.f+1; 66
67 if(tx<1||tx>h||ty<1||ty>w)//越界
68 continue; 69
70 if(e[tx][ty]=='X')//撞牆
71 continue; 72
73 if(!book[tx][ty])//須要沒走過
74 { 75 book[tx][ty]=1;//標記
76 q.push({tx,ty,tf});//導入隊列
77
78 if(e[tx][ty]==endd)//找到終點了 (顯然在這裏找終點比在隊首找終點要快)
79 { 80 startx=tx;//把如今終點刷新爲下一次bfs起點,很關鍵!!
81 starty=ty; 82 return tf;//return步數
83 } 84
85 } 86
87 } 88 q.pop(); 89 } 90 //return -1;//這裏確定找獲得終點,不須要寫這個
91 } 92
93 int main() 94 { 95 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 96
97 cin>>h>>w>>n; 98
99 for(int i=1;i<=h;i++) 100 { 101 for(int j=1;j<=w;j++) 102 { 103 cin>>e[i][j];//讀入地圖
104 if(e[i][j]=='S')//找到起點
105 { 106 startx=i;//標記目前第一個起點
107 starty=j; 108 } 109 } 110 } 111
112 ll int ans=0; 113
114 for(int i=1;i<=n;i++) 115 { 116 ans+=bfs(char(i+'0'));//n次bfs,每次起點終點都不一樣 117 //cout<<i<<" "<<ans<<endl; 118 //getchar();
119 } 120
121 cout<<ans<<endl; 122
123 return 0; 124 }