跳到正文

题解

BFS题解:P10379 [GESP202403 七级] 俄罗斯方块

zealot527约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P10379

版本

  1. v2当前
  2. v1

思路:把每个块的位置相等起始块的位置组成字符串,作为唯一id来比对 BFS代码

C++
#include<iostream>
#include<queue>
#include<set>
using namespace std;
const int N=502;
int a[N][N];
bool f[N][N];
int n,m;
struct point{
	int x,y;
};
set<string> s;
string bfs(point b)
{
	string str="";
	int k=a[b.x][b.y];
	int dx[5]={0,1,-1,0,0};
	int dy[5]={0,0,0,1,-1};
	queue<point> dl;
	dl.push(b);
	while(!dl.empty())
	{
		point t=dl.front();
		str+=to_string(b.x-t.x);//相对起点位置记录
		str+=to_string(b.y-t.y);//相对起点位置记录
		dl.pop();
		for(int i=1;i<=4;i++)
		{
			int tx=t.x+dx[i];
			int ty=t.y+dy[i];
			if(tx>=1 && tx<=n && ty>=1 && ty<=m)//不出范围
			{
				if(!f[tx][ty] && k==a[tx][ty])//能走且数值一样
				{
					f[tx][ty]=1;//标记已走
					dl.push({tx,ty});
				}
			}
		}
	}
	return str;
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			cin>>a[i][j];
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
		{
			if(!f[i][j])
			{
				f[i][j]=1;//起点标记已走
				string st=bfs({i,j});
				s.insert(st);
			}
		}
//	for(auto x:s)
//		cout<<x<<endl;
	cout<<s.size();
	return 0;
}
原文