数独(dfs+剪枝)

博客围绕数独问题展开,题目是在九宫格中填数,使横行、纵行和每一块都包含1 - 9。解题思路采用深搜,用col和row记录横行、纵行未用的数,cell标记未用的数,通过剪枝找到某个数可填的最小可能,还给出了代码。

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

题目:数独

参考:yxc
题意:就是给你一个九宫格,让你填数,使横行包含1 ~ 9,纵行包含1 ~ 9,每一块包含1 ~ 9 。
思路:本题采用深搜,然后通过用col和row分别记录横行和纵行没有被用过的数,cell来标记没有被用过的数,通过0代表这个数已经被用过了,1代表这个数没有被用过,然后通过剪枝找到某个数可以填数的最小可能,这个最小可能通过row[x] & cell[x/3][y/3] & col[y]来找到。
代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100;
const int N = 9;
char str[maxn];
int cell[10][10],row[maxn],col[maxn];
int mp[1<<N], ones[1<<N];
int lowbit(int x)
{
    return x&(-x);
}
void set_init()
{
    for(int i = 0; i < N; i++ )mp[1<<i] = i;
    for(int i = 0; i < 1<<N; i++)
    {
        int cn = 0;
        for(int j = i; j; j -= lowbit(j))cn++;
        ones[i] = cn;
    }
}
void init()
{
    for(int i = 0; i < N; i++)row[i] = (1<<N)-1, col[i] = (1<<N)-1;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            cell[i][j] = (1<<N)-1;
}
int judge(int x, int y)
{
    return row[x] & cell[x/3][y/3] & col[y];
}
bool dfs(int cnt)
{
    if(!cnt)return true;
    int minn = 10, x, y;
    for(int i = 0; i < N; i++)//找到最小的能填数的位置
    {
        for(int j = 0; j < N; j++)
        {
            if(str[i*N+j] == '.')
            {
                int t = ones[judge(i, j)];
                if(minn > t)minn = t, x = i, y = j;
            }
        }
    }
    for(int i = judge(x, y); i; i -= lowbit(i))
    {
        int t = mp[lowbit(i)];
        row[x] -= 1<<t;
        col[y] -= 1<<t;
        cell[x/3][y/3] -= 1<<t;
        str[x*N+y] = '1'+ t;
        if(dfs(cnt-1))return true;
        row[x] += 1<<t;//恢复现场
        col[y] += 1<< t;
        cell[x/3][y/3] += 1<<t;
        str[x*N+y] = '.';
    }
    return false;
}
int main()
{
    set_init();//预处理
    while(cin>>str && strcmp(str, "end") != 0)
    {
        init();//初始化为全1
        int cnt = 0;
        for(int i = 0, k = 0; i < N; i++)
        {
            for(int j = 0; j < N; j++, k++)
            {
                if(str[k] != '.')
                {
                    int t = str[k] - '1';
                    row[i] -= 1<<t;
                    col[j] -= 1<<t;
                    cell[i/3][j/3] -= 1<<t;
                }
                else cnt++;
            }
        }
        dfs(cnt);
        printf("%s\n", str);
    }
    return 0;
}
### 关于DFS剪枝在蓝桥杯竞赛中的应用 #### 什么是DFS剪枝? 深度优先搜索(Depth-First Search, DFS)是一种常见的遍历或搜索树或图的算法。然而,在实际问题中,由于状态空间可能非常庞大,单纯的DFS可能会导致时间复杂度过高甚至超时。因此,引入了剪枝技术来减少不必要的计算。通过提前判断某些分支不可能达到最优解并将其舍弃,从而显著提升效率。 #### 剪枝的应用场景 在蓝桥杯竞赛中,DFS常用于解决组合、排列、路径规划等问题。而剪枝则可以通过以下方式实现优化: 1. **可行性剪枝**:当当前状态下已经无法满足题目条件时,立即停止继续探索该分支。 2. **最优性剪枝**:对于寻找最小值或最大值的问题,如果发现某个分支的结果无论如何都不会优于已知的最佳结果,则可以直接跳过此分支。 --- #### 示例代码分析 以下是基于蓝桥杯常见题型的一个典型DFS剪枝实例: ##### 数独游戏 数独是一个经典的约束满足问题,适合用DFS求解。为了加速搜索过程,可以在每次放置数字前先验证其合法性,并利用一些启发式策略进一步缩小搜索范围。 ```java public class SudokuSolver { private final int[][] board; public SudokuSolver(int[][] initialBoard) { this.board = initialBoard; } public boolean solve() { return dfs(0); } private boolean dfs(int pos) { if (pos >= 81) return true; // 如果填满了整个棋盘,返回成功 int row = pos / 9, col = pos % 9; if (board[row][col] != 0) return dfs(pos + 1); // 当前位置已有预设值,跳过 for (int num = 1; num <= 9; ++num) { if (isValid(row, col, num)) { // 判断当前位置是否合法 board[row][col] = num; // 尝试填充数字 if (dfs(pos + 1)) return true; // 继续递归尝试下一格 board[row][col] = 0; // 回溯操作 } } return false; // 所有候选数字均失败,回退至上一层级 } private boolean isValid(int r, int c, int n) { for (int i = 0; i < 9; ++i) { if (board[r][i] == n || board[i][c] == n) return false; // 行列冲突检测 } int startRow = 3 * (r / 3), startCol = 3 * (c / 3); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (board[startRow + i][startCol + j] == n) return false; // 子网格冲突检测 } } return true; } } ``` 上述代码实现了基本的数独求解器,并加入了简单的剪枝逻辑以排除非法的状态转移[^1]。 --- ##### 权重分配问题 另一个典型的例子来自砝码称重问题。假设给定若干不同重量的砝码以及目标总质量M,问是否存在一种方案使得这些砝码能够恰好组成指定的质量。此类问题可通过DFS枚举所有可能性,同时加入合理的剪枝条件降低冗余运算量。 ```cpp #include <bits/stdc++.h> using namespace std; bool canWeigh(vector<int>& weights, int targetWeight, int index, int currentSum) { if (currentSum == targetWeight) return true; // 达到目标即终止 if (index >= weights.size()) return false; // 超出数组边界也结束 bool result = false; // 不选当前砝码的情况 result |= canWeigh(weights, targetWeight, index + 1, currentSum); // 只有当不会超过上限才考虑选用当前砝码 if (currentSum + weights[index] <= targetWeight && !result) { result |= canWeigh(weights, targetWeight, index + 1, currentSum + weights[index]); } return result; } int main(){ vector<int> wts{1, 2, 4}; cout << (canWeigh(wts, 7, 0, 0)? "Yes": "No") << endl; return 0; } ``` 在此程序片段里,我们不仅限定了递归层数还设置了额外限制防止无意义扩展[^2]。 --- ##### Python版路径之谜 最后来看一道涉及方向控制与重复访问规避的任务。“路径之谜”要求模拟一位骑士按照特定规则穿越迷宫的过程。这里采用广度优先搜索配合记忆化存储机制完成任务。 ```python def find_path(north_arrows, west_arrows): from collections import deque visited = [[False]*len(north_arrows[0]) for _ in range(len(north_arrows))] queue = deque([(0, 0)]) # 初始化起点坐标 while queue: x, y = queue.popleft() if not (0<=x<len(north_arrows) and 0<=y<len(north_arrows[0])) or visited[x][y]: continue visited[x][y]=True north_count=north_arrows[x][y]-sum([visited[k][y]for k in range(x)]) west_count=west_arrows[x][y]-sum([visited[x][l]for l in range(y)]) if abs(north_count)+abs(west_count)>0: possible_moves=[(-north_count<0),(west_count<0)] if any(possible_moves):queue.extend(((x+(not p)*p,y+p*p)for p in possible_moves)) return 'Possible'if all(all(rw)for rw in visited[:-1]):else:'Impossible' ``` 这段脚本展示了如何借助队列结构逐步展开潜在轨迹直至找到符合条件的一条为止[^4]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值