Sudoku Solver without recursion

hey guys, how can i eliminate recursion in this C code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
 
int grid[9][9];
 
void print_solution(void)
{
  static int nsol = 0;
  int r, c;
 
  printf("----- solution %d -----\n", ++nsol);
  for (r = 0; r < 9; r++)
  {
    for (c = 0; c < 9; c++)
    {
      printf("%d", grid[r][c]);
      if (c % 3 == 2) printf("  ");
    }
    printf("\n");
    if (r % 3 == 2) printf("\n");
  }
 
}
 
int safe(int row, int col, int n)
{
  int r, c, br, bc;
 
  if (grid[row][col] == n) return 1;
  if (grid[row][col] != 0) return 0;
  for (c = 0; c < 9; c++)
    if (grid[row][c] == n) return 0;
  for (r = 0; r < 9; r++)
    if (grid[r][col] == n) return 0;
  br = row / 3;
  bc = col / 3;
  for (r = br * 3; r < (br + 1) * 3; r++)
    for (c = bc * 3; c < (bc + 1) * 3; c++)
      if (grid[r][c] == n) return 0;
 
  return 1;
}
 
void solve(int row, int col)
{
  int n, t;
 
  if (row == 9)
    print_solution();
  else
    for (n = 1; n <= 9; n++)
      if (safe(row, col, n)) {
	t = grid[row][col];
	grid[row][col] = n;
	if (col == 8)
	  solve(row + 1, 0);
	else
	  solve(row, col + 1);
 
	grid[row][col] = t;
      }
}
 
int
main()
{
  int i, j;
 
  printf("enter the sudoku: \n");
  for(i=0;i<9;i++)
    for(j=0;j<9;j++)
    {
      printf("(%d, %d): ", i+1, j+1);
      scanf("%d", &grid[i][j]);
    }
  solve(0,0);
  return 0;
}
you need to input your own puzzle but you can also
use this text files below to automatically
do it for you... in the command prompt type:

solver.exe<puzzle1.txt

note: puzzle2.txt is difficult to solve
      it is near worst case.

[puzzle1.txt]
9 0 0 0 0 7 1 0 0
0 0 0 8 0 2 0 7 0
5 7 0 1 6 3 0 0 0
0 0 5 4 0 0 9 3 6
0 0 1 0 0 0 2 0 0
3 2 6 0 0 9 8 0 0
0 0 0 9 1 6 0 8 3
0 6 0 3 0 5 0 0 0
0 0 3 2 0 0 0 0 1

[puzzle2.txt]
0 0 0 0 0 0 0 0 0
0 0 0 0 0 3 0 8 5
0 0 1 0 2 0 0 0 0
0 0 0 5 0 7 0 0 0
0 0 4 0 0 0 1 0 0
0 9 0 0 0 0 0 0 0
5 0 0 0 0 0 0 7 3
0 0 2 0 1 0 0 0 0
0 0 0 0 4 0 0 0 9
Recursion of this nature can always be eliminated by use of an internal stack.
what is internal stack? sorry for being ignorant. what i mean here to how to recode this without recursion, maybe use loops..
I am not entirely sure but I think jsmith is referring to the stack container adapter which is a LIFO container. Deque is the normal container it is adapted onto but you can also use vectors or lists. You can find it in <stack>. What's so bad about recursion anyway?
i've done it.. using for loop yey :) .. except it can only solve the first possible answer not all possible answers :(

i'm still open to your suggestions guys
Last edited on
Topic archived. No new replies allowed.