2022.3.20
作者:互联网
蓝书
AcWing 194. 涂满它!
比完赛后补题解
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int N = 1e5 + 10, INF = 1e8;
int n, a[10][10], vis[10][10];
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
int check()
{
int cnt = 0, tot[6] = {0};
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!tot[a[i][j]] && vis[i][j] != 1)
{
tot[a[i][j]] = 1;
cnt++;
}
}
}
return cnt;
}
void paint(int x, int y, int color)
{
vis[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i], yy = y + dy[i];
if (xx < 0 || xx >= n || yy < 0 || yy >= n || vis[xx][yy] == 1)
continue;
vis[xx][yy] = 2;
if (a[xx][yy] == color)
paint(xx, yy, color);
}
}
int change(int color)
{
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
if (a[i][j] == color && vis[i][j] == 2)
{
cnt++;
paint(i, j, color);
}
}
return cnt;
}
bool dfs(int dep, int cnt)
{
if (cnt + check()> dep)
{
return 0;
}
if (!check())
return 1;
int back[10][10];
for (int i = 0; i < 6; i++)
{
memcpy(back, vis, sizeof vis);
if (change(i) && dfs(dep, cnt + 1))
return 1;
memcpy(vis, back, sizeof vis);
}
return 0;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
while (cin >> n && n)
{
memset(vis, 0, sizeof vis);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> a[i][j];
int dep = 0;
paint(0, 0, a[0][0]);
while (dep <= 50)
{
if (dfs(dep, 0))
break;
dep++;
}
cout << dep << '\n';
}
return 0;
}
标签:cnt,20,int,++,yy,vis,xx,2022.3 来源: https://www.cnblogs.com/menitrust/p/16031245.html