每日一题(PTAL2-052):吉利矩阵--dfs

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int res=0;
int sum_row[4]={0};
int sum_col[4]={0};
void dfs(int x,int sum,int width){
    if(x==width*width){
        ++res;
        return;
    }
    for(int i=0;i<=sum;i++){
        if(x % width ==width-1 && i!=sum-sum_row[x / width])continue;
        if(x / width ==width-1 && i!=sum-sum_col[x % width])continue;
        if(sum_row[x / width]+i<=sum && sum_col[x % width]+i<=sum){
            sum_col[x % width]+=i;sum_row[x/width]+=i;
            dfs(x+1,sum,width);
            sum_col[x % width]-=i;sum_row[x/width]-=i;
        }
    } 
}
int main(){
    int sum,width;
    cin>>sum>>width;
    dfs(0,sum,width);
    cout<<res;
    return 0;
}

注意点:

1 利用全局变量res存储个数。

2 和岛屿类似 这里用for循环进行寻找每种情况,并通过一加一减进行回溯

相关推荐
数研小生1 天前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克1 天前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手1 天前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.1 天前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
爱看科技1 天前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
qq_417129251 天前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao1 天前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
吴维炜1 天前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
辰尘_星启1 天前
[线性代数]矩阵/向量求导为什么要区别分子布局和分母布局
神经网络·线性代数·数学·矩阵·控制·导数
Σίσυφος19001 天前
PCL Point-to-Point ICP详解
人工智能·算法