1359:圍成面積


題目鏈接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1359

【思路分析】這個題屬於逆向思維,直接統計圍成面積很難,換種思路,將面積以外的所有0點置1再統計0數即為圍成面積,這樣就轉換成4連通塊的問題了!當然這兒有個小思考就是外圍面積置1時一定要從4條邊緣開始找0點BFS,所以需要將BFS寫成一個函數。代碼如下:

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 const int n=10;
 5 int a[n+5][n+5];
 6 int nex[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
 7 int ans=0;
 8 struct m{
 9     int x;
10     int y;
11 }f, t;
12 void bfs(int xx, int yy)
13 {
14     queue<m> q;
15     t.x=xx; t.y=yy;
16     a[t.x][t.y]=1;
17     q.push(t);
18     while(!q.empty())
19     {
20         f=q.front();
21         for(int k=0; k<4; k++)
22         {
23             int nx=f.x+nex[k][0];
24             int ny=f.y+nex[k][1];
25             if(nx>=0 && nx<n && ny>=0 && ny<n && a[nx][ny]==0)
26             {
27                 a[nx][ny]=1;
28                 t.x=nx;  t.y=ny;
29                 q.push(t);
30             }
31         }
32         q.pop();
33     }    
34 }
35 
36 int main()
37 {
38     
39     for(int i=0; i<n; i++)
40         for(int j=0; j<n; j++)
41             cin>>a[i][j];
42     
43     for(int j=0;j<=9;j++)//以上邊緣開始bfs置1 
44         if(a[0][j]==0)bfs(0,j);
45     for(int j=0;j<=9;j++)//以下邊緣開始bfs置1 
46         if(a[9][j]==0)bfs(9,j);
47     for(int i=0;i<=9;i++)//以左邊緣開始bfs置1 
48         if(a[0][i]==0)bfs(0,i);
49     for(int i=0;i<=9;i++)//以右邊緣開始bfs置1 
50         if(a[9][i]==0)bfs(9,i);
51 //以下注釋為測試代碼 
52 //cout<<endl;
53 //    for(int i=0; i<n; i++){
54 //        for(int j=0; j<n; j++)cout<<a[i][j]<<" ";
55 //        cout<<endl;
56 //    }
57     for(int i=0; i<n; i++)//最后統計沒有置1的所有的點,即面積點數 
58         for(int j=0; j<n; j++)
59             if(a[i][j]==0)++ans;    
60     cout<<ans;
61     return 0;
62 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM