上进小青年

导航

DFS与BFS

顾名思义,DFS就是一直在一个方向搜索,当这一方向不可以时退回该点,换下一方向; 而BFS一开始就是向四面八方搜索,把符合条件的点存入队列中,当前一个点都搜索完毕时,再从队列顶中取出点,再向四面八方搜索。

HRBUST1143 http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1143

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<string.h>
 5 #include<queue>
 6 using namespace std;
 7 int m,n,p,q;
 8 int ma[1010][1010],vis[1010][1010];
 9 int dx[4]={1,0,-1,0};
10 int dy[4]={0,-1,0,1};
11 int ans;
12 bool check(int x,int y){
13 if(x>0&&y>0&&x<=m&&y<=n&&ma[x][y]<=ma[p][q]&&vis[x][y]==0)
14     return true;
15 else return false;
16 }
17 int dfs(int x,int y)
18 {
19   vis[x][y]=1;
20   ans++;
21 for(int i=0;i<4;i++){
22     int sx=x+dx[i];
23     int sy=y+dy[i];
24     if(check(sx,sy))
25         dfs(sx,sy);
26 }
27 
28 }
29 int main(){
30 
31 while(~scanf("%d%d%d%d",&m,&n,&p,&q)){
32        ans=0;
33 memset(vis,0,sizeof(vis));
34 memset(ma,0,sizeof(ma));
35     for(int i=1;i<=m;i++){
36         for(int j=1;j<=n;j++){
37             cin>>ma[i][j];
38         }
39     }dfs(p,q);
40    cout<<ans<<endl;
41 }
42 }
View Code
 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<string.h>
 5 #include<queue>
 6 using namespace std;
 7 int shu[1005][1005],m,n,p,q,ans;
 8 int mov[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
 9 int vis[1005][1005];
10 struct point{
11     int x;int y;
12 };
13 bool check(point a){
14 if(a.x>0&&a.y>0&&a.x<=m&&a.y<=n&&vis[a.x][a.y]==0&&shu[a.x][a.y]<=shu[p][q]){
15     return true;
16 
17 }
18 else return false;
19 }
20 
21 int bfs(int x,int y){
22     queue<point>que;
23     int coun=1;
24     point now,temp;
25     now.x=x;
26     now.y=y;
27     que.push(now);
28     vis[x][y]=1;
29 while(!que.empty()){
30     temp=que.front();
31     que.pop();
32     for(int k=0;k<4;k++){
33         now.x=temp.x+mov[k][0];
34         now.y=temp.y+mov[k][1];
35         if(check(now)){
36             que.push(now);
37             vis[now.x][now.y]=1;
38             //cout<<now.x<<" "<<now.y<<endl;
39             coun++;
40         }
41     }
42 }return coun;
43 }
44 int main(){
45 while(~scanf("%d%d%d%d",&m,&n,&p,&q)){
46         memset(shu,0,sizeof(shu));
47     for(int i=1;i<=m;i++){
48         for(int j=1;j<=n;j++){
49             cin>>shu[i][j];
50         }
51     }
52     memset(vis,0,sizeof(vis));
53 
54 
55     cout<<bfs(p,q)<<endl;
56 }
57 }
View Code

 

上面是我写的代码,输出是对的啊,但是不知道为什么就是不过,若是有大神看见啦希望帮我改一改啊^...^

 

posted on 2016-08-03 15:01  上进小青年  阅读(200)  评论(0编辑  收藏  举报