UVA 11520 - Fill the Square (暴力)

本文介绍了一种通过暴力搜索解决填字游戏的方法。利用DFS遍历所有可能的组合,确保每个空位填充字典序最小的字母,实现游戏的解决。详细代码和时间复杂度分析提供。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该题直接暴力即可,因为一定有解,所以对每一个空格,尽可能的放置字典序小的字母就行了。

虽然用dfs写的,但是时间复杂度是显然的,最高只有O(n*n*26)。

细节参加代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 100000000;
const int maxn = 50 + 5;
int T,n,kase = 0;
char s[maxn][maxn];
bool dfs(int r, int c) {
    if(r == n && c == n+1) {
        for(int i=1;i<=n;i++) printf("%s\n",s[i]+1);
        return true;
    }
    if(c == n+1) { r++; c = 1; }
    for(int i=r;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            if(s[i][j] == '.') {
                for(int k=0;k<26;k++) {
                    char cc = 'A'+k;
                    bool ok = true;
                    if(i > 1 && s[i-1][j] == cc) ok = false;
                    if(j > 1 && s[i][j-1] == cc) ok = false;
                    if(i < n && s[i+1][j] == cc) ok = false;
                    if(j < n && s[i][j+1] == cc) ok = false;
                    if(ok) {
                        s[i][j] = cc;
                        if(dfs(i,j+1)) return true;
                    }
                }
            }
            if(i == n && j == n) if(dfs(n,n+1)) return true;
        }
    }
    return false;
}
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&n);
        for(int i=1;i<=n;i++) {
            scanf("%s",s[i]+1);
        }
        printf("Case %d:\n",++kase);
        dfs(1,1);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值