第三部分 數據結構 -- 第二章 隊列-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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章