标签:des style blog http color io os java ar
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1295 Accepted Submission(s): 618
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <vector> 6 #include <queue> 7 using namespace std; 8 9 #define N 105 10 11 char map[N][N]; 12 int visited[N][N][1<<4]; 13 int n, m, k; 14 int xx[]={1,-1,0,0}; 15 int yy[]={0,0,1,-1}; 16 17 struct node{ 18 int x, y, pr, t; 19 }; 20 21 int bfs(int stx,int sty){ 22 memset(visited,0,sizeof(visited)); 23 node p, q; 24 int i, j; 25 queue<node>Q; 26 p.x=stx;p.y=sty;p.pr=0;p.t=0; 27 visited[p.x][p.y][p.pr]=1; 28 Q.push(p); 29 while(!Q.empty()){ 30 p=Q.front(); 31 Q.pop(); 32 if(p.pr==(1<<k)-1) return p.t; //当遍历完k个坐标就return 33 34 for(i=0;i<4;i++){ 35 p.x+=xx[i]; 36 p.y+=yy[i]; 37 if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&map[p.x][p.y]!=‘#‘&&!visited[p.x][p.y][p.pr]){ 38 visited[p.x][p.y][p.pr]=1; 39 if(map[p.x][p.y]!=‘.‘){ //当走到给的k个坐标处 40 if(p.pr&(1<<(map[p.x][p.y]-‘0‘))){ //已经走过该坐标 41 p.t+=1; 42 Q.push(p); 43 p.t-=1; 44 } 45 else{ //没走过该坐标 46 int u=p.pr; 47 p.pr=p.pr|(1<<(map[p.x][p.y]-‘0‘)); 48 p.t+=1; 49 visited[p.x][p.y][p.pr]=1; 50 Q.push(p); 51 p.t-=1; 52 p.pr=u; 53 } 54 } 55 else{ 56 p.t+=1; 57 Q.push(p); 58 p.t-=1; 59 } 60 } 61 p.x-=xx[i]; 62 p.y-=yy[i]; 63 } 64 65 } 66 return -1; 67 } 68 69 main() 70 { 71 int i, j, x, y; 72 while(scanf("%d %d",&n,&m)==2){ 73 if(!n&&!m) break; 74 for(i=0;i<n;i++) scanf("%s",map[i]); 75 int stx, sty, f=0; 76 for(i=0;i<n;i++){ 77 for(j=0;j<m;j++){ 78 if(map[i][j]==‘@‘){ 79 stx=i;sty=j;f=1;break; 80 } 81 }if(f) break; 82 } 83 scanf("%d",&k); 84 f=0;int cnt=0, ka=k; 85 while(ka--){ 86 scanf("%d %d",&x,&y); 87 x--;y--; 88 if(f) continue; 89 if(map[x][y]==‘#‘){ //若给的坐标处为墙,肯定没法遍历完k个坐标 90 f=1; 91 } 92 else{ 93 map[x][y]=cnt+‘0‘; 94 cnt++; 95 } 96 } 97 if(f) { 98 printf("-1\n");continue; 99 } 100 int ans=bfs(stx,sty); 101 if(ans!=-1) printf("%d\n",ans); 102 else printf("-1\n"); 103 } 104 }
标签:des style blog http color io os java ar
原文地址:http://www.cnblogs.com/qq1012662902/p/3990393.html