NYoj WAJUEJI which home strong!(简单搜索)

题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=1100

这道题,自己初写搜索,给学长气的只打我,Orz.......

搜索的思路要理清楚!

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<algorithm>
 5 #include<iostream>
 6 #include<ctype.h>
 7 #include<iomanip>
 8 #include<queue>
 9 #include<stdlib.h>
10 using namespace std;
11 int T,n,m; 12 int bx,by,ex,ey; 13 int map[101][101]; 14 int ans[101][101]; 15 int dx[4]={0,0,1,-1}; 16 int dy[4]={1,-1,0,0}; 17 int temp2=0,temp3=-1; 18 19 struct node //优先队列 20 { 21 int x,y; 22 int fei; 23 friend bool operator < (node a, node b) //优先步数少的 24 { 25 return a.fei > b.fei; 26 } 27 }; 28 29 int bfs(int a,int b) 30 { 31 priority_queue<node> q; 32 node s1,s2; 33 s1.x=a; 34 s1.y=b; 35 s1.fei=0; 36 q.push(s1);//入队 37 while(!q.empty()) 38 { 39 s1=q.top();//取出队顶元素 40 q.pop();删除队顶元素 41 if(s1.x==ex&&s1.y==ey) 42 { 43 return s1.fei; 44 } 45 for(int i=0;i<4;i++) //四个方向搜索 46 { 47 s2.x=s1.x+dx[i]; 48 s2.y=s1.y+dy[i]; 49 if(map[s2.x][s2.y]!=-1&&s2.x>=0&&s2.x<n&&s2.y>=0&&s2.y<m) 50 { 51 s2.fei=s1.fei+map[s2.x][s2.y]; 52 map[s2.x][s2.y]=-1; 53 q.push(s2); 54 } 55 } 56 } 57 return -1; 58 } 59 60 int main() 61 { 62 scanf("%d",&T); 63 while(T--) 64 { 65 scanf("%d %d",&n,&m); 66 char temp; 67 for(int i=0;i<n;i++) //再次感受到世界是数字的 68 { 69 for(int j=0;j<m;j++) 70 { 71 cin>>temp; 72 if(temp=='#') 73 { 74 map[i][j]=-1; 75 } 76 if(temp>='A'&&temp<='Z') 77 { 78 map[i][j]=temp-'A'+1; 79 } 80 if(temp=='s') 81 { 82 bx=i; 83 by=j; 84 map[i][j]=0; 85 } 86 if(temp=='l') 87 { 88 ex=i; 89 ey=j; 90 map[i][j]=0; 91 } 92 } 93 } 94 temp3=bfs(bx,by); 95 printf("%d\n",temp3); 96 } 97 }

 

posted @ 2015-09-29 14:29  Vmetrio  阅读(230)  评论(0编辑  收藏  举报