Go program

Description

A little like Go, the day he wanted to design a whim Go game, but a basic question is: how to calculate the area bounded by a line segment is closed it?

In the following example, the composition of 5 * 5 "01" in the board, by a "1" surrounded by the "0" of the area is: 3.

0 0 0 0 0
0 1 1 1 1
0 1 0 1 0
1 0 0 1 1
1 1 1 1 0

Provisions: calculated statistical area "1" surrounded by a closed curve in the number of horizontal and vertical lines of intersection, in particular, 0 is not calculated at the edge, "0" as the third row of five is not counted area.

Input

A board 10 * 10 matrix, each point of the board composed of 0,1.

Output

1 is intended to output from the title area enclosed 0.

Sample Input

0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 1
0 0 0 1 1 1 0 0 0 0
0 0 0 1 0 0 1 1 1 0
0 0 0 0 1 1 0 0 0 1
0 0 0 0 0 1 0 0 1 0
0 0 0 1 1 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0
0 0 0 0 1 1 1 0 0 0
0 0 0 0 1 1 1 0 0 0

Sample Output

12
 1 #include<iostream>
 2 //#include<fstream>
 3 using namespace std;
 4 int a[100][100];
 5 int dir[4][2]={1,0,0,-1,-1,0,0,1};
 6 void dfs(int x,int y){
 7     a[x][y]=1;
 8     int dx,dy;
 9     for(int i=0;i<4;i++){
10         dx=x+dir[i][0];
11         dy=y+dir[i][1];
12         if(dx>=1&&dx<=10&&dy>=1&&dy<=10&&!a[dx][dy])
13             dfs(dx,dy);
14     }
15 }
16 int main(){
17     int ans=0;
18     //fstream file("haha.txt");
19     for(int i=1;i<=10;i++){
20         for(int j=1;j<=10;j++){
21             //file>>a[i][j];
22             cin>>a[i][j];
23         }
24     }
25     for(int i=1;i<=10;i++){
26         if(!a[1][i])    dfs(1,i);
27         if(!a[10][i])    dfs(10,i);
28         if(!a[i][1])    dfs(i,1);
29         if(!a[i][10])    dfs(i,10);
30     }
31     for(int i=1;i<=10;i++){
32         for(int j=1;j<=10;j++){
33             if(!a[i][j])
34                 ans++;
35         }
36     }
37     cout<<ans<<endl;
38     return 0;
39 }
View Code

 

首先说方法,我们要把圈外的0都变成1,然后遍历整个数组数一数一共有几个0那么围成的面积就是几

然后说一下怎么实现,主体思想是用dfs或者bfs,因为我们只想把圈外的0变成1,所以我们从边缘开始搜索

    for(int i=1;i<=10;i++){
        if(!a[1][i])    dfs(1,i);
        if(!a[10][i])    dfs(10,i);
        if(!a[i][1])    dfs(i,1);
        if(!a[i][10])    dfs(i,10);
    }

这个代码实现的就是这一块,注意必须要从边缘开始,不能遍历整个数组搜索,如果遍历整个数组搜索的话,数组里所有的0都会变成1了。

然后就是dfs的思想,上下左右连一块的算连着,斜着的不算,从边缘开始,所有连着的0变成1。





Guess you like

Origin www.cnblogs.com/fate-/p/12233487.html