Encountered a problem very pit, pit me a long time (cry!): Output, printf ( "% d \ n", ans); one less line breaks, Results mistake, I too hard! ! !
The whole idea is very simple to determine the source node to 1, 1 to 2, ... n-1 to n minimum spend, you can add up, that is n times bfs it.
1 #include<cstring> 2 #include<iostream> 3 #include<queue> 4 #include<algorithm> 5 #include<cstdio> 6 7 using namespace std; 8 9 typedef pair<int,int> P; 10 const int INF=100000000; 11 int h,w,n; 12 char maze[1005][1005]; 13 int d[1005][1005]; 14 int dx[4]={1,-1,0,0}; 15 int dy[4]={0,0,-1,1}; 16 int ans; 17 18 int bfs(char charstart,char charend){ 19 int x,y; 20 for(int i=0;i<h;i++){ 21 for(int j=0;j<w;j++){ 22 if(maze[i][j]==charstart){ 23 x=i;y=j; 24 } 25 } 26 } 27 queue<P> que; 28 que.push(P(x,y)); 29 while(que.size()){ 30 x=que.front().first; 31 y=que.front().second; 32 que.pop(); 33 if(maze[x][y]==charend){ 34 return d[x][y]; 35 } 36 for(int i=0;i<4;i++){ 37 int nx=x+dx[i],ny=y+dy[i]; 38 if(0<=nx&&nx<h&&ny>=0&&ny<w&&d[nx][ny]==0&&maze[nx][ny]!='X'){ 39 d[nx][ny]=d[x][y]+1; 40 que.push(P(nx,ny)); 41 } 42 } 43 } 44 } 45 46 void solve(){ 47 scanf("%d%d%d",&h,&w,&n); 48 for(int i=0;i<h;i++){ 49 for(int j=0;j<w;j++){ 50 cin >> maze[i][j]; 51 } 52 } 53 ans+=bfs('S','1'); 54 for(int i=1;i<=n-1;i++){ 55 memset(d,0,sizeof(d)); 56 char s = char(i+48); 57 char e = char(i+1+48); 58 ans+=bfs(s,e); 59 } 60 printf("%d\n",ans); 61 } 62 63 int main(){ 64 solve(); 65 return 0; 66 }