Quote (Minkomonster @ Mar 18 2014 07:15pm)
Anyone that sees this do me a favor, OP PM'd me and said he tried running the above code and it bombed out. Can anyone try to compile/run and see if you can replicate this? Because I cannot. He says he copied it exactly.
Just tried running it, gives me a segfault when I input a number.
gdb:
Code
952374816
839761452
521893764
786512349
267435198
145986237
413628975
698147523
374259681
4
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff726cdc7 in _IO_vfscanf_internal (s=<optimized out>, format=<optimized out>,
argptr=argptr@entry=0x7fffffffdc98, errp=errp@entry=0x0) at vfscanf.c:1826
1826 vfscanf.c: No such file or directory.
(gdb) bt
#0 0x00007ffff726cdc7 in _IO_vfscanf_internal (s=<optimized out>, format=<optimized out>,
argptr=argptr@entry=0x7fffffffdc98, errp=errp@entry=0x0) at vfscanf.c:1826
#1 0x00007ffff727bb1b in __scanf (format=<optimized out>) at scanf.c:33
#2 0x0000000000400f05 in main () at sudoku.cpp:98
Looks like you're just trying to scanf and putting the variable into nothing which is why it's dying. Just replace scanf("%d") with getchar(); at the end.
Adjusted code:
Code
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <algorithm>
bool randomize(int* row, int n)
{
for(int i = 0; i < n; i++) row[i] = i+1;
std::random_shuffle(&row[0],&row[n]);
}
bool unassigned(int** grid, int n, int& r, int& c)
{
for(r = 0; r < n; r++)
for(c = 0; c < n; c++)
if(grid[r][c] == 0)
return true;
return false;
}
bool conflicts(int** grid,int n, int r, int c, int x)
{
for(int i = 0; i < n; i++)
if(grid[r][i] == x || grid[i][c] == x) return true;
return false;
}
bool solve(int** grid, int n)
{
int r, c;
//if there are no unassigned cells then the
//grid has been completely solved
if(!unassigned(grid,n,r,c))
return true;
//generate a list of candidates for this cell, and randomize it
int cand[n];
randomize(cand,n);
int ncand = n;
//otherwise, choose a random value for this cell and attempt to solve
for(int i = cand[0]; ncand > 0; ncand--)
{
//ensure there are no conflicts with this value
if(!conflicts(grid,n,r,c,i))
{
//assign the value to this cell
grid[r][c] = i;
//attempt to recursively solve every remaining unassigned cell
if(solve(grid,n))
{
//if the board is completely solved we return true
return true;
}
//otherwise this value was not correct. reset and continue
grid[r][c] = 0;
//remove candidate
cand[0] = cand[ncand-1];
}
}
//we have exhausted all possibilities for this cell and did not
//obtain a solved board, so backtrack and try again
return false;
}
int main()
{
srand (time(NULL));
int n = 9;
int* grid[n];
for(int i = 0; i < n; i++)
{
grid[i] = new int[n];
for(int j = 0; j < n; j++)
grid[i][j] = 0;
}
//solve the board using backtracking
solve(grid,n);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
printf("%d",grid[i][j]);
printf("\n");
}
getchar();
}
This post was edited by xXZyZXx on Mar 18 2014 10:57pm