2023年码蹄杯二1赛 小码哥玩游戏 题型:搜索

71 阅读1分钟

码题集OJ-小码哥玩游戏 (matiji.net)

刚开始我用的bfs(),只能过部分数据:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
int n, m;
char op;
char s[110][110];
int vis[110][110];
int cnt;
int dx[] = { 0,1,0,-1 }, dy[] = { -1,0,1,0 };
void dfs(int x,int y)
{
	memset(vis, -1, sizeof vis);
	queue<PII>q;
	q.push({ x,y });
	vis[x][y] = 1;

	while (!q.empty())
	{
		PII t=q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int tx = x + dx[i], ty = y + dy[i];
			if (tx<0 || tx>=n || ty<0 || ty>=m || vis[tx][ty] != -1 || s[tx][ty] == op||s[tx][ty]=='0')continue;

			q.push({ tx,ty });
			vis[tx][ty] = 1;
			cnt++;
		}
	}
}
int main()
{
	cin >> n >> m >> op;

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> s[i][j];

	   }
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (s[i][j] == op)
			{
				dfs(i, j);
			}			

		}
	}
	cout << cnt;

	return 0;
**}**

image.png

原因是没有考虑去重,

image.png

#include<bits/stdc++.h>
using namespace std;
int n, m;
char op;
const int N = 110;
char g[N][N];
set<char>se;
int main()
{
	memset(g,'0',sizeof g);
	cin >> n >> m >> op;

	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> g[i][j];
	
	
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (g[i][j] != op)continue;

				se.insert(g[i - 1][j]);
				se.insert(g[i + 1][j]);
				se.insert(g[i][j - 1]);
				se.insert(g[i][j + 1]);
			
		}
	}

        
       //去重

	if (se.count(op)!=0)
	{
		se.erase(op);
	}
	if(se.count('0') != 0)
	{
		se.erase('0');
	}

	cout << se.size();
	return 0;
}

image.png