BFS 搜索 蓝桥杯模拟赛

题目链接: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;
} 

 

posted @ 2019-02-02 15:28  stul  阅读(132)  评论(0编辑  收藏  举报