Image Perimeters[BFS]

Description

给出一张由"x"和".“组成的矩阵。每个"x"可以向上下左右及两个斜对角进行连通,请问由某个点开始的"x”,它所连通的图形的周长为多少。

Input

整个测试有多组数据,整个测试以四个零代表结束。
对于每个数据,第一行给出整个图形的大小(长度小于50),再给出开始点的坐标。接下来若干行用于描述这个图形。

Output

如题

Sample Input

2 2 2 2
XX
XX
6 4 2 3
.XXX
.XXX
.XXX
…X
…X.
X…
5 6 1 3
.XXXX.
X…X
…XX.X
.X…X
…XXX.
7 7 2 6
XXXXXXX
XX…XX
X…X…X
X…X…
X…X…X
X…X
XXXXXXX
7 7 4 4
XXXXXXX
XX…XX
X…X…X
X…X…
X…X…X
X…X
XXXXXXX
0 0 0 0

Sample Output

8
18
40
48
8

这道题是找连通块,只是多了斜线,算周长只要在四周打点,ans++,剩下就是BFS日常操作。

八个方向:

int dir[8][2]={{0,1},{1,0},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};

结构体:

struct node{
	int x;
	int y;
	node(){ };
	node (int sx,int sy){
		x=sx;
		y=sy;
	}
};

BFS主体:

void bfs(int x,int y){
	q1.push(node(x,y));
	vis[x][y]=1;
	while(!q.empty()){
		node prg = q.front();
		q.pop();
		
		
		for(int i=0;i<8;i++){
			int tx = prg.x+dir[i][0];
			int ty = prg.y+dir[i][1]; 
		
		
			if(!vis[tx][ty]&&mp[tx][ty] == 'X'){
				q.push(node(tx,ty));
				q1.push(node(tx,ty));
				vis[tx][ty]=1;
			}
		}
	} 
}

打点,计算答案:

void change(){
	for(int i=0;i<=n+1;i++){
		for(int j=0;j<=m+1;j++){
			if(mp[i][j]!='X'&&mp[i][j]!='.'){
					mp[i][j]='.';
			}
		}
	}
		q.push(node(x,y));
		bfs(x,y);
	while(!q1.empty()){
			node prg = q1.front();
			q1.pop();
		for(int i=0;i<4;i++){
				int tx=prg.x+dir[i][0];
				int ty=prg.y+dir[i][1];
			if(mp[tx][ty]=='.'){
					ans++;
			}
		}
	}
}

完整代码:

#include<bits/stdc++.h>
using namespace std;

int ans=0;

int dir[8][2]={{0,1},{1,0},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};

struct node{
	int x;
	int y;
	node(){ };
	node (int sx,int sy){
		x=sx;
		y=sy;
	}
};

char mp[1001][1001];
bool vis[1001][1001];


queue<node> q;
queue<node> q1;


void bfs(int x,int y){
	q1.push(node(x,y));
	vis[x][y]=1;
	while(!q.empty()){
		node prg = q.front();
		q.pop();
		
		
		for(int i=0;i<8;i++){
			int tx = prg.x+dir[i][0];
			int ty = prg.y+dir[i][1]; 
		
		
			if(!vis[tx][ty]&&mp[tx][ty] == 'X'){
				q.push(node(tx,ty));
				q1.push(node(tx,ty));
				vis[tx][ty]=1;
			}
		}
	} 
}

int n,m,x,y;

void change(){
	for(int i=0;i<=n+1;i++){
		for(int j=0;j<=m+1;j++){
			if(mp[i][j]!='X'&&mp[i][j]!='.'){
					mp[i][j]='.';
			}
		}
	}
		q.push(node(x,y));
		bfs(x,y);
	while(!q1.empty()){
			node prg = q1.front();
			q1.pop();
		for(int i=0;i<4;i++){
				int tx=prg.x+dir[i][0];
				int ty=prg.y+dir[i][1];
			if(mp[tx][ty]=='.'){
					ans++;
			}
		}
	}
}

int main(){
	
	while(cin >> n >> m>> x>>y&&n&&m){
		
		ans=false;
		
		memset(vis,0,sizeof vis);
        memset(mp,'\0',sizeof mp);
		
		
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				cin >> mp[i][j];
			}
		} 
		change();
		cout<< ans << endl;
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值