Image Perimeters POJ - 1111(bfs)

时间:2019-02-11
本文章向大家介绍Image Perimeters POJ - 1111(bfs),主要包括Image Perimeters POJ - 1111(bfs)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

解题思路:本题是求含有X块的周长,即要求出在边缘的X和旁边有**.**的X,只要在结点出队的时候加以判断即可。

#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

struct Node
{
	int x, y;
};

queue<Node> Q;
char map[20][20];
bool mark[20][20]; 
int go[][2] = {1,0, -1,0, 0,1, 0,-1, 1,1, 1,-1, -1,-1, -1,1};

int BFS(int n, int m)
{
	Node now;
	int x, y, num = 0;
	while(!Q.empty())
	{
		now = Q.front();
		Q.pop();
		
		//边界上的点 
		if(now.x == 0)
			num++;
		if(now.x == n-1)
			num++;
		if(now.y == 0)
			num++;
		if(now.y == m-1)
			num++;
		
		//x的上下左右四个方向是否有.	
		for(int i = 0; i < 4; i++)
		{
			x = now.x + go[i][0];
			y = now.y + go[i][1];
			if(x < 0 || x >= n || y < 0 || y >= m)
				continue;
			if(map[x][y] == '.')
				num++;
		}
		for(int i = 0; i < 8; i++)
		{
			x = now.x + go[i][0];
			y = now.y + go[i][1];
			if(x < 0 || x >= n || y < 0 || y >= m)
				continue;
			if(map[x][y] == '.' || mark[x][y] == true)
				continue;
			Node tmp;
			tmp.x = x, tmp.y = y;
			mark[x][y] = true;
			Q.push(tmp);
		}
	} 
	return num;
}

int main()
{
	int n, m, x, y;
	while(scanf("%d %d %d %d", &n, &m, &x, &y))
	{
		if(n == 0)
		 	break;
		for(int i = 0; i < n; i++)
			scanf("%s", map[i]);
		while(!Q.empty())
			Q.pop();
		
		memset(mark, 0, sizeof(mark));
		
		if(map[x-1][y-1] == '.')
			printf("0\n");
		else
		{
			Node start;
			start.x = x-1, start.y = y-1;
			mark[x-1][y-1] = true;
			Q.push(start);
			printf("%d\n", BFS(n, m));
		}
	}
	
	return 0;
}