Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <math.h>
- using namespace std;
- const int MAX_N = 10;
- int size, idx;
- int grid[MAX_N][MAX_N];
- int id_area[MAX_N][MAX_N];
- bool area[MAX_N][10];
- void get_areas_id(void)
- {
- for (int i = 0; i < size; i += sqrt(size)) {
- for (int j = 0; j < size; j += sqrt(size)) {
- for (int k = i; k < i + sqrt(size); k++) {
- for (int l = j; l < j + sqrt(size); l++) {
- id_area[k][l] = idx;
- }
- }
- idx++;
- }
- }
- // This is to quickly check if a number is already in an area
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- if (grid[i][j] != 0) {
- area[id_area[i][j]][grid[i][j]] = true;
- }
- }
- }
- return;
- }
- bool can_place(int val, int x, int y)
- {
- // Check current row
- for (int i = 0; i < size; i++) {
- if (grid[x][i] == val) {
- return false;
- }
- }
- // Check current column
- for (int i = 0; i < size; i++) {
- if (grid[i][y] == val) {
- return false;
- }
- }
- // Check current area
- if (area[id_area[x][y]][val]) {
- return false;
- }
- return true;
- }
- bool empty_cell(int &x, int &y)
- {
- for (x = 0; x < size; x++) {
- for (y = 0; y < size; y++) {
- if (grid[x][y] == 0) {
- return true;
- }
- }
- }
- return false;
- }
- bool fill(void)
- {
- int x, y;
- if (!empty_cell(x, y)) { // Sudoku solved
- return true;
- }
- for (int val = 1; val <= size; val++) {
- if (can_place(val, x, y)) {
- grid[x][y] = val;
- area[id_area[x][y]][val] = true;
- if (fill()) {
- return true;
- }
- // Reset
- area[id_area[x][y]][val] = false;
- grid[x][y] = 0;
- }
- }
- return false;
- }
- int main()
- {
- ios::sync_with_stdio(false);
- cin.tie(0); cout.tie(0);
- // Input
- cin >> size;
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- cin >> grid[i][j];
- }
- }
- get_areas_id();
- fill();
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- cout << grid[i][j] << " ";
- }
- cout << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement