洛谷 1451:求细胞数目 经典广搜题

#include<iostream>
#include<cstdio>
#include<ctime>
using namespace std;

// Groups
int map[101][101];
int storage_x[1001];
int storage_y[1001];
int move_x[4] = {-1,0,1,0};
int move_y[4] = {0,1,0,-1};
	
// Singles
int m,n;
int number_of_cells;
	
// Functions
void breadth_first_search(int,int);

int main()
{
	scanf("%d %d\n",&m,&n);
	
	for(int i = 0 ; i < m ; ++i)
		for(int j = 0 ; j < n ; ++j)
			map[i][j] = 1;
		
	char str[101];		
		for(int p = 0 ; p < m ; ++p)
		{
			scanf("%s",str);
			
			for(int q = 0 ; q < n ; ++q)
				if(str[q] == '0')	
					map[p][q] = 0;
		};

	//clock_t START = clock(); 
		
	for(int w = 0 ; w < m ; ++w)
		for(int v = 0 ; v < n ; ++v)
			if(map[w][v])
				breadth_first_search(w,v);			
			
	printf("%d\n",number_of_cells);		
	
	//clock_t END = clock();
	
	//printf("\nTime = %.2f\n",(double)(END - START) / CLOCKS_PER_SEC);		
			
	return 0;
};

void breadth_first_search(int x,int y)
{
	++number_of_cells;
	
	int head = 0;
	int tail = 1;
	
	map[x][y] = 0;
	
	storage_x[tail] = x;
	storage_y[tail] = y;
	
	while(head < tail)
	{
		++head;
		
		for(int i = 0 ; i < 4 ; ++i)
		{
			int buffer_x = storage_x[head] + move_x[i];
			int buffer_y = storage_y[head] + move_y[i];
			
			if(buffer_x >= 0 && buffer_x <= m && buffer_y >= 0 && buffer_y <= n)
				if(map[buffer_x][buffer_y])
				{
					++tail;
					
					storage_x[tail] = buffer_x;
					storage_y[tail] = buffer_y;
					
					map[buffer_x][buffer_y] = 0;
				};
		};
	};
};

猜你喜欢

转载自blog.csdn.net/LynlinBoy/article/details/82149201