第三部分 数据结构 -- 第二章 队列-1359:围成面积

1359:围成面积

时间限制: 1000 ms 内存限制: 65536 KB
提交数: 4423 通过数: 1992
【题目描述】
编程计算由“”号围成的下列图形的面积。面积计算方法是统计号所围成的闭合曲线中水平线和垂直线交点的数目。如下图所示,在10×10的二维数组中,有“*”围住了15个点,因此面积为15。

在这里插入图片描述

【输入】
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
【输出样例】
15


思路:以上边缘开始bfs置1,以下边缘开始bfs置1,以左边缘开始bfs置1,以右边缘开始bfs置1 ,最后统计没有置1的所有的点,即面积点数 .

#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
const int N = 10 + 5;
int a[N][N];
int n  = 10;
int dx[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int ans = 0;
struct node{
	int x;
	int y;
	
}f,t;
void bfs(int xx, int yy){
	queue<node> q;
	t.x = xx;
	t.y = yy;
	a[t.x][t.y] = 1;
	q.push(t);
	while(!q.empty()){
		f = q.front();
		for(int k = 0; k < 4; k++){
			int nx = f.x + dx[k][0];
			int ny = f.y + dx[k][1];
			if(nx >= 0 && nx < n && ny >= 0 && ny < n && !a[nx][ny]  )
			{
				a[nx][ny] = 1;
				t.x = nx;
				t.y = ny;
				q.push(t);
			}
		}
		q.pop();
	} 
}
int main(){
	for(int i = 0; i < n; i++)
	   for(int j = 0; j < n; j++)
	  cin >> a[i][j];
	  
	  for(int j = 0 ; j <= 9 ;j++)//以上边缘开始bfs置1
	    if(a[0][j] == 0) bfs(0,j);
	    
	  for(int j = 0 ; j <= 9 ;j++) //以下边缘开始bfs置1
	    if(a[9][j] == 0) bfs(9,j);
	    
	  for(int i = 0 ; i <= 9 ;i++) //以左边缘开始bfs置1
	    if(a[0][i] == 0) bfs(0,i);
	    
	  for(int i = 0 ; i <= 9 ;i++)//以右边缘开始bfs置1 
	    if(a[9][i] == 0) bfs(9,i);
	    
	for(int i = 0 ; i < n ;i++)//最后统计没有置1的所有的点,即面积点数 
	   for(int j = 0; j < n; j++)
	     if(a[i][j] == 0) ++ans;
	     cout << ans;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章