计算水池数目

原题目链接:原题目

采用广度优先算法来做

为了简单起见,不从标准输入读取数据,数据在代码中指定

代码如下:

 1 #include <iostream>
 2 #include <list>
 3 using namespace std;
 4 #define COLUMN_NUMBER 5
 5 #define ROW_NUMBER 5
 6 
 7 int get_count(const int (*data)[COLUMN_NUMBER]);
 8 
 9 struct Point {
10     int x;
11     int y;
12     Point(int x,int y)
13     {
14         this->x = x;
15         this->y = y;
16     }
17     Point(){}
18 
19 };
20 
21 int main()
22 {
23     int data[ROW_NUMBER][COLUMN_NUMBER] = {{1,1,1,1,0},
24                                           {0,0,1,0,1},
25                                           {0,0,0,0,0},
26                                           {1,1,1,0,0},
27                                           {0,0,1,1,1}};
28     int count = get_count(data);
29     cout << "count = " << count << endl;
30     return 0;
31 }
32 
33 
34 int get_count(const int (*data)[COLUMN_NUMBER])
35 {
36     int count = 0;
37     int is_travelled[ROW_NUMBER][COLUMN_NUMBER] = {0};
38 
39     for(int i = 0;i < ROW_NUMBER;++i)
40     {
41         for(int j = 0;j < COLUMN_NUMBER;++j)
42         {
43             //if it is a pool and is has not been travelled
44             if(1 == data[i][j] && 0 == is_travelled[i][j])
45             {
46                 ++count;
47 
48                 is_travelled[i][j] = 1;//make it been travelled
49                 list<Point> vec;
50                 Point p(i,j);
51                 vec.push_back(p);
52                 while(!vec.empty())
53                 {
54                     Point current_point = vec.front();//get the first element
55                     vec.erase(vec.begin());//delete the first element
56                     //get the four neighor coordinates
57                     int left_top_x = current_point.x == 0 ? 0 : current_point.x -1 ;
58                     int left_top_y = current_point.y == 0 ? 0 : current_point.y - 1;
59                     int right_bottom_x = current_point.x == ROW_NUMBER - 1 ? ROW_NUMBER - 1 : current_point.x + 1;
60                     int right_bottom_y = current_point.y == COLUMN_NUMBER - 1 ? COLUMN_NUMBER - 1 : current_point.y + 1;
61 
62                     Point vertex[4];
63                     vertex[0] = Point(left_top_x,current_point.y);
64                     vertex[1] = Point(right_bottom_x,current_point.y);
65                     vertex[2] = Point(current_point.x,left_top_y);
66                     vertex[3] = Point(current_point.x,right_bottom_y);
67 
68                     for(int i = 0; i < 4;++i)
69                     {
70                         Point _p = vertex[i];
71                         if(0 == is_travelled[_p.x][_p.y] && 1 == data[_p.x][_p.y])
72                             vec.push_back(_p);
73                         is_travelled[_p.x][_p.y] = 1;
74                     }
75                 }
76             }
77         }
78     }
79 
80     return count;
81 
82 }

 

posted @ 2015-07-03 14:40  RIO_2607  阅读(361)  评论(0编辑  收藏  举报