I’m only getting the first subgrid solved in the output, can anyone point out what’s wrong here?
#include <bits/stdc++.h>
#define vi vector<int>
#define dvi vector<vector<int>>
#define b begin
#define e end
#define ff first
#define ss second
#define viit vector<int>::iterator
using namespace std;
void peek (dvi vec) {
for(auto i:vec) {
for(auto j:i) cout << j;
cout << endl;
}
}
vi options (dvi grid, int i, int j, int n) {
vi o_vec;
if(grid[i][j]) return o_vec;
for(int m=1;m<=9;m++) o_vec.push_back(m);
for(int x=0;x<n;x++) {
viit it = find(o_vec.b(),o_vec.e(),grid[x][j]);
if(it!=o_vec.e()) o_vec.erase(it);
}
for(int y=0;y<n;y++) {
viit it = find(o_vec.b(),o_vec.e(),grid[i][y]);
if(it!=o_vec.e()) o_vec.erase(it);
}
int d=3;
int sub = n/d, si = (i/sub)*sub, sj = (j/sub)*sub;
for(int x=si;x<si+sub;x++) {
for(int y=sj;y<sj+sub;y++) {
viit it = find(o_vec.b(),o_vec.e(),grid[x][y]);
if(it!=o_vec.e()) o_vec.erase(it);
}
}
return o_vec;
}
bool sudoku (dvi& grid, int j, int n) {
if(j==n) return true;
else {
for(int i=0;i<n;i++) {
vi opt = options(grid,i,j,n);
if(opt.size()) {
for(int k=0;k<opt.size();k++) {
grid[i][j] = opt[k];
if(sudoku(grid,j+1,n)) return true;
}
grid[i][j] = 0;
}
}
}
return false;
}
void sudoku_util(dvi& grid) {
int n = grid.size();
sudoku(grid,0,n);
}
int main () {
dvi grid = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
sudoku_util(grid);
peek(grid);
return 0;
}
Output:
316528490
529104706
487000031
003010080
900863005
050090600
130000250
000000074
005206300