Description
编程计算由“ * ”号围成的下列图形的面积。面积计算方法是统计号所围成的闭合曲线中水平线和垂直线交点的数目。如下图所示,在1010的二维数组中,有“ * ”围住了15个点,因此面积为15。
0 0 0 0 0 0 0 0 0 0
0 0 0 0 * * * 0 0 0
0 0 0 0 * 0 0 * 0 0
0 0 0 0 0 * 0 0 * 0
0 0 * 0 0 0 * 0 * 0
0 * 0 * 0 * 0 0 * 0
0 * 0 0 * * 0 * * 0
0 0 * 0 0 0 0 * 0 0
0 0 0 * * * * * 0 0
0 0 0 0 0 0 0 0 0 0
Input
第一行包括两个整数n和m,代表矩形的行数和列数。(n和m均不超过100)
接下来n行,每行m个整数,其中用1来代表*。
Output
输出所求的面积。
Sample Input
10 10
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0
0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 1 0 1 0
0 1 0 1 0 1 0 0 1 0
0 1 0 0 1 1 0 1 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0
Sample Output
15
Solution
第一反应是用bfs来写, 从圈外的第一个0(该点记为now)开始,将now = -1并入队,向上下左右四个方向进行搜索(搜索到点记为next),如果next == 0,则将next = -1并入队。最后,在搜索结束之后遍历整个数组,找出所有的0,即为所求的面积。
但是这里有一个小小的问题是封闭图形外的0并不一定是一整块,所以如果只从一个点开始搜索必然是不能把所有的圈外0都处理到。这个问题我就用最不动脑子的暴力方法来解决了,直接把整个矩阵四边的每一个点作为起点搜一遍,这样一定可以覆盖到所有的圈外0。
下面是代码:
#include <bits/stdc++.h>
using namespace std;
int n, m;
int Map[110][110];
int dir[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
struct crd
{
int x, y;
};
void bfs(crd start)
{
if (Map[start.x][start.y]) //如果该点不为0,则不作为起点
return;
else //否则作为起点
Map[start.x][start.y] = -1;
queue<crd> q;
q.push(start);
while (!q.empty())
{
crd now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = now.x + dir[i][0];
int y = now.y + dir[i][1];
if (x >= 0 && x < n && y >= 0 && y < m && Map[x][y] == 0)
{
Map[x][y] = -1;
crd next = { x, y };
q.push(next);
}
}
}
}
int main()
{
while (cin >> n >> m)
{
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> Map[i][j];
for (int i = 0; i < n; i++) //把左右两条边作为起点
{
bfs({ i, 0 });
bfs({ i, m-1 });
}
for (int i = 0; i < m; i++) //把上下两条边作为起点
{
bfs({ 0, i });
bfs({ n-1, i });
}
for (int i = 0; i < n; i++) //统计处理过后所有的0
{
for (int j = 0; j < m; j++)
{
if (Map[i][j] == 0)
ans++;
}
}
cout << ans << endl;
}
return 0;
}
还有一种解决方法是在这个矩阵的外面围一圈0,以(0,0)作为起点开始,用bfs将所有的0都染成-1,最后再统计剩余0的个数。这种做法相较上面而言更优,省去了搜索四边来寻找起点的这一步。
下面是代码:
#include <bits/stdc++.h>
#define mms(a, b) memset(a, b, sizeof(a))
using namespace std;
int n, m;
int Map[110][110];
int dir[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
struct crd
{
int x, y;
};
void bfs(crd start)
{
queue<crd> q;
q.push(start);
while (!q.empty())
{
crd now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = now.x + dir[i][0];
int y = now.y + dir[i][1];
if (x >= 0 && x <= n + 1 && y >= 0 && y <= m + 1 && Map[x][y] == 0)
{
Map[x][y] = -1;
crd next = { x, y };
q.push(next);
}
}
}
}
int main()
{
while (cin >> n >> m)
{
int ans = 0;
mms(Map, 0);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> Map[i][j];
bfs({ 0, 0 });
for (int i = 1; i <= n; i++) //统计处理过后所有的0
{
for (int j = 1; j <= m; j++)
{
if (Map[i][j] == 0)
ans++;
}
}
cout << ans << endl;
}
return 0;
}