这个镇上,有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 }