Sudoku backtracking algorithm

后端 未结 6 1951
感动是毒
感动是毒 2020-12-03 03:55

First of all, I\'ll state that this is a university assignment so I\'m not asking for someone to write the code for me I just need to be pointed in the right direction. :)

6条回答
  •  無奈伤痛
    2020-12-03 04:40

    as @ralu mentioned, the fastest algorithm to solve sudoku is using DLX. below is a program i wrote in the past. it can solve 4*4 sudoku within 1 second.

    suppose the input is like:

    --A----C-----O-I
    -J--A-B-P-CGF-H-
    --D--F-I-E----P-
    -G-EL-H----M-J--
    ----E----C--G---
    -I--K-GA-B---E-J
    D-GP--J-F----A--
    -E---C-B--DP--O-
    E--F-M--D--L-K-A
    -C--------O-I-L-
    H-P-C--F-A--B---
    ---G-OD---J----H
    K---J----H-A-P-L
    --B--P--E--K--A-
    -H--B--K--FI-C--
    --F---C--D--H-N-
    
    
    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    const int INF=1<<30;
    const int N=4;
    const int MAXR=N*N*N*N*N*N+10;
    const int MAXC=N*N*N*N*4+10;
    const int SIZE=MAXR*MAXC/N/N;
    
    int n,m;
    int mat[MAXR][MAXC],r,c,ans;
    int L[SIZE],R[SIZE],U[SIZE],D[SIZE],S[MAXC],C[SIZE],RH[SIZE],O[MAXC];
    int a[MAXR];
    char b[MAXR];
    char s[N*N+10][N*N+10];
    int head,cnt;
    
    int node(int up,int down,int left,int right) {
        U[cnt]=up;D[cnt]=down;L[cnt]=left;R[cnt]=right;
        D[up]=U[down]=L[right]=R[left]=cnt;
        return cnt++;
    }
    
    void init() {
        cnt=0;
        head=node(0,0,0,0);
        for (int i=1;i<=c;i++) {
            C[i]=node(cnt,cnt,L[head],head);
            S[i]=0;
        }
        for (int i=1;i<=r;i++) {
            int rowh=-1;
            for (int j=1;j<=c;j++) if (mat[i][j]) {
                if (rowh==-1) {
                    rowh=node(U[C[j]],C[j],cnt,cnt);
                    RH[rowh]=i;
                    C[rowh]=C[j];
                    S[j]++;
                }
                else {
                    int k=node(U[C[j]],C[j],L[rowh],rowh);
                    RH[k]=i;
                    C[k]=C[j];
                    S[j]++;
                }
            }
        }
    }
    
    void remove(int col) {
        L[R[col]]=L[col];
        R[L[col]]=R[col];
        for (int i=D[col];i!=col;i=D[i])
            for (int j=R[i];j!=i;j=R[j]) {
                U[D[j]]=U[j];
                D[U[j]]=D[j];
                S[C[j]]--;
            }
    }
    
    void resume(int col) {
        for (int i=U[col];i!=col;i=U[i])
            for (int j=L[i];j!=i;j=L[j]) {
                S[C[j]]++;
                U[D[j]]=j;
                D[U[j]]=j;
            }
        L[R[col]]=col;
        R[L[col]]=col;
    }
    
    bool dfs(int k) {
        if (R[head]==head) {
            ans=k;
            return true;
        }
        int mins=INF,cur=0;
        for (int i=R[head];i!=head;i=R[i])
            if (S[i]a[O[j]]) swap(O[i],O[j]);
    
            for (int i=0;i

    u can have a try :)

提交回复
热议问题