廣度優先搜尋的代碼

來源:互聯網
上載者:User
我這次還沒有理解
#include<iostream>#include<cstdio>#include<cstring>#include<queue>   //包含隊列使用using namespace std;int dir[8][2]={{1,0},{0,1},{-1,0},{0,-1},{1,-1},{-1,1},{1,1},{-1,-1}};//同樣是用dir控制方向char G[101][101];  //存資料bool vis[101][101];//標記int n,m;           //注意。此處依題意,m為行,n為列,與之前講過的代碼相反void BFS(int si,int sj){ //si sj為廣搜起始點的座標      queue<int>Q;      Q.push(si);  //將座標入隊列,先行(i),後列(j)      Q.push(sj);      vis[si][sj]=1;//將起點標記      while(!Q.empty()){ //當隊列非空時,持續進行搜尋            int x=Q.front();Q.pop(); //將對首的點取出            int y=Q.front();Q.pop();                        for(int i=0;i<8;i++){   //此處與dfs相同,訪問8個方向                  int fx=x+dir[i][0];                  int fy=y+dir[i][1];                  if(fx>=0&&fx<m&&fy>=0&&fy<n){                        if(G[fx][fy]=='@'&&!vis[fx][fy]){                              vis[fx][fy]=1;                              Q.push(fx);//與dfs不同的是,dfs在此時進行遞迴調用                              Q.push(fy);//而bfs進行的是入隊操作。                        }                  }            }      }}int main(){//主函數部分,與dfs基本相同。      while(scanf("%d%d",&m,&n)!=EOF&&(m||n)){            memset(vis,0,sizeof(vis));            for(int i=0;i<m;i++){                  scanf("%s",G[i]);            }            int sum=0;            for(int i=0;i<m;i++)            for(int j=0;j<n;j++){                  if(!vis[i][j]&&G[i][j]=='@'){                        BFS(i,j);                        sum++;                  }            }            cout<<sum<<endl;      }      return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.