HJ 44 Sudoku-Java

Ideas:

Recursively.

Using deep traversal, according to the vertical and horizontal, 3X3, jump out of the candidate number, and then continue to traverse according to this number, if it meets the requirements that do not meet the requirements, return, use the next candidate number,

The last number in the last line is successfully resolved.

Title description

Problem description: Sudoku is a popular digital logic game. Players need to calculate the numbers of all the remaining spaces based on the known numbers on the 9X9 board, and satisfy that the numbers in each row, column, and each thick-line palace contain 1-9, and do not repeat.
Input:
9X9 disk array containing known numbers [vacancies are represented by the number 0]
Output:
complete 9X9 disk array

Example:

#include<iostream>
#include<unordered_set>
using namespace std;

int s[9][9];
bool bingo = false;

void dfs(int i=0, int j=0)
{
    if(i >= 9) {
        bingo = true;
        return ;
    }
    if(s[i][j] == 0) {
        unordered_set<int> exist;
        for(int h = 0; h < 9; h++) {
            exist.insert(s[i][h]);
            exist.insert(s[h][j]);
        }
        int in = i / 3 * 3, jn = j / 3 * 3;
        for(int h = in; h/3*3 < in+1; h++) {
            for(int k = jn; k/3*3 < jn+1; k++) {
                exist.insert(s[h][k]);
            }
        }
        if(exist.size() == 10) return ;
        for(int digit = 1; digit <= 9; digit++) {
            if(exist.count(digit) == 0) {
                s[i][j] = digit;
                dfs(i+(j/8), (j+1)%9);
                if(!bingo) {
                    s[i][j] = 0;
                } else {
                    break;
                }
            }
        }
    } else {
        dfs(i+(j/8), (j+1)%9);
    }
}

int main() 
{
    for(int i = 0; i < 9; i++) {
        for(int j = 0; j < 9; j++) {
            cin >> s[i][j];
        }
    }
    dfs();
    for(int i = 0; i < 9; i++) {
        for(int j = 0; j < 9; j++) {
            cout << s[i][j] << (j==8?"\n":" ");
        }
    }
}

 

Guess you like

Origin blog.csdn.net/u012571715/article/details/115045143