神棍节献礼之——POJ1111 Image Perimeters(bfs)

题很简单,广搜,深搜自己随意就好。

BFS 代码:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

#define N 31

int n,m,mat[N][N],vis[N][N];
int dir[8][2]={-1,0, 1,0, 0,-1, 0,1, -1,-1, -1,1, 1,-1, 1,1};

struct node{
	int x,y;
};

int judge(int x,int y){
	if(x>=1 && y>=1 && x<=n && y<=m)return 1;
	return 0;
}
/*只有当搜到边界时,才需要统计边数!!!*/
void bfs(int x,int y){
	queue<node> q;
	int i;
	memset(vis,0,sizeof(vis));
	node cur,next;
	cur.x=x; cur.y=y;
	vis[cur.x][cur.y]=1;
	q.push(cur);
	int sum=0;
	while(!q.empty()){
		cur=q.front();
		q.pop();
		for(i=0;i<8;i++){
			next.x=cur.x+dir[i][0];
			next.y=cur.y+dir[i][1];
			if(vis[next.x][next.y]==1)continue;
			if(judge(next.x,next.y) && mat[next.x][next.y]){//在界内 且 可达
				vis[next.x][next.y]=1;
				q.push(next);
			}
			else if(i<4)sum++;
			/*八个方向中,只有上下左右需要考虑边界,剩下的四个方向的边界对sum值没有影响*/
		}
	}
	printf("%d\n",sum);
}
int main()
{
	int i,j,x,y;
	char ch[2];
	while(scanf("%d%d%d%d",&n,&m,&x,&y),n){
		memset(mat,0,sizeof(mat));
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++){
				scanf("%1s",ch);
				if(ch[0]=='.')mat[i][j]=0;
				else mat[i][j]=1;
			}
		}
		if(mat[x][y]==0)puts("0");
		else bfs(x,y);
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值