首页 > 其他 > 详细

BFS 搜索 蓝桥杯模拟赛

时间:2019-02-02 16:08:03      阅读:192      评论:0      收藏:0      [点我收藏+]

题目链接:https://nanti.jisuanke.com/t/36117

 

这个题目想不到用广搜来做,一直在想深搜。

广搜的思路呢,是把最外圈不是黑色(不是0)的数 的位置 i 和 j 进队,赋值为0。然后依次用广搜对最外圈的这些非0点向四个方向搜索。大于0的就继续进队,赋值为0。

100%通过 代码

#include <bits/stdc++.h>
#define M 505
using namespace std;
int arr[M][M];
int m,n;

int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
queue<pair<int,int> >q;

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>m>>n;
		for(int i = 0; i < m; i++)
			for(int j = 0; j < n; j++)
			{
				scanf("%d",&arr[i][j]);
				if((i == 0 || i == m-1 || j == 0 || j == n-1) && arr[i][j] > 0)
					q.push(make_pair(i,j)),arr[i][j] = 0;
			}
		while(!q.empty())
		{
			int x = q.front().first;
			int y = q.front().second;
			q.pop();
			for(int i = 0; i < 4; i++)
			{
				int dx = x + dir[i][0];
				int dy = y + dir[i][1];
				if(arr[dx][dy] > 0 && dx < m && dx >= 0 && dy < n && dy >= 0)
					q.push(make_pair(dx,dy)),arr[dx][dy] = 0;
			}
		}
		for(int i = 0; i < m; i++)
		{
			for(int j = 0; j < n; j++)
				if(j) cout<<" "<<arr[i][j];	
				else cout<<arr[i][j];
			cout<<"\n";
		}
			
	}
	return 0;
} 

 

BFS 搜索 蓝桥杯模拟赛

原文:https://www.cnblogs.com/stul/p/10348531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!