求助
查看原帖
求助
764344
zenght楼主2023/10/19 23:05

dfs连通块写法,样例没过求调,写了一个小时了

#include <cstdio>
#include <cstring>
using namespace std;

int n, k;
char c[120][12];
bool vis[120][12], v[120][12];
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};

int in(int x, int y)
{
	return x >= 1 && x <= n && y >= 1 && y <= 10;
}

int dfs(int x, int y)
{
	int ans = 1;
	for (int i = 0; i < 4; i++)
	{
		int nx = x + dx[i];
		int ny = y + dy[i];
		if (in(nx, ny) && c[x][y] == c[nx][ny] && !vis[nx][ny])
		{
			vis[nx][ny] = true;
			ans += dfs(nx, ny);
		}
	}
	return ans;
}

void turn(int x, int y)
{
	for (int i = 0; i < 4; i++)
	{
		int nx = x + dx[i];
		int ny = y + dy[i];
		if (in(nx, ny) && c[x][y] == c[nx][ny] && !vis[nx][ny])
		{
			v[nx][ny] = true;
			turn(nx, ny);
		}
	} 
}

bool chk()
{
	bool ra = false;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= 10; j++)
			if (c[i][j] != '0' && !vis[i][j])
				if (dfs(i, j) >= k)
				{
					ra = true;
					v[i][j] = true;
					turn(i, j);
				}
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= 10; j++)
			if (v[i][j]) c[i][j] = '0';
	return ra;
}

int main()
{
	scanf("%d%d", &n, &k);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= 10; j++)
			scanf(" %c", &c[i][j]);
	while (chk())
	{
		memset(vis, false, sizeof(vis));
		memset(v, false, sizeof(v));
		for (int j = 1; j <= 10; j++)
		{
			int cur = n + 1;
			for (int i = n; i >= 1; i--)
				if (c[i][j] != '0')
				{
					c[--cur][j] = c[i][j];
					c[i][j] = '0';
				}
		}
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= 10; j++)
			printf("%c", c[i][j]);
		printf("\n");
	}
	return 0;
}

CSP2023 rp++

2023/10/19 23:05
加载中...