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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值