天天看點

計蒜客藍橋杯模拟賽5 九宮格

問題描述

将數字 1…9 填入一個 3×3 的九宮格中,

使得格子中每一橫行和的值全部相等,每一豎列和的值全部相等。請你計算有多少種填數字的方案

思路:就9個數,全排列時間也是夠的,是以直接全排列吧,不需要剪枝,麻煩

代碼:

int f[];
int a[];
int c = ;
void dfs(int step){
    if(step==){
        int row1 = a[]+a[]+a[];
        int row2 = a[]+a[]+a[];
        int row3 = a[]+a[]+a[];
        int col1 = a[]+a[]+a[];
        int col2 = a[]+a[]+a[];
        int col3 = a[]+a[]+a[];
        if(row1==row2&&row2==row3&&col1==col2&&col2==col3){
            c++;
        }
        return;
    }
    for(int i = ;i<=9;i++){
        if(!f[i]){
            a[step] = i;
            f[i] = ;
            dfs(step+);
            a[step] = ;
            f[i] = ;
        }
    }
}
int main(){
    dfs();
    printf("%d\n",c);//72答案
    return ;
}