HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

4x4 Sudoku solver performance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
solversudoku4x4performance

Problem

The code is for a 4x4 Sudoku solver. It works fine when there are a small number of unfilled spaces (0's) but when I give the whole matrix input as 0's or so the solver takes a very long time. I need it to give only the first valid output, no need to calculate the rest of the outputs.

I input a matrix with values from 0 to 4. If they are from 1 to 4 then they are prefilled and they cannot be changed. But if the value is 0, then we can change and fill in any values from 1 to 4 so that once the Sudoku is filled validly we get the output else the program prints "No".

Matrix A contains the inputs. Matrix B contains either 1's or 0's. If the value is 0 at location x and y in matrix B, then that means that that value is not prefilled.

```
#include
#include

void printd(int A[4][4])
{
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%d", A[i][j]);
}
printf("\n");
}
printf("\n");
return;
}

int check(int A[4][4])
{
int i,j,k,a,b,c,state=1,temp=1;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(A[i][j]==0)
temp=2;
}
}
if(temp==1)
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
for(a=0;a<4;a++)
{
if(a!=i && A[i][j]==A[a][j])
state=0;
if(a!=j && A[i][j]==A[i][a])
state=0;
if(i<2 && j<2)
{
for(b=0;b<2;b++)
{
for(c=0;c<2;c++)
{
if((b!=i || c!=j) && A[i][j]==A[b][c])
state=0;
}
}
}
else if(i<2 && j<4)
{
for(b=0;b<2;b++)
{
for(c=2;c<4;c++)
{
if((b!=i || c!=

Solution

The formatting is messy:

  • Many unexpectedly indented blocks and lines. Use indenting well to improve readability, by clearly identifying nested blocks of code.



  • Put a space after commas in variable lists and parameter lists, for example:



  • Instead of int n,i,j,k,a,b,c,d prefer int n, i, j, k, a, b, c, d



  • Instead of fill(A,B,0,0) prefer fill(A, B, 0, 0)



  • Put a space around operators, for example:



  • Instead of for(i=0;i



  • Instead of if(A[i][j]!=0) prefer if (A[i][j] != 0)



The number 4 is magic in this code.
It's everywhere.
If you ever extend your implementation to a 5x5 matrix or other,
you will have to replace that everywhere.
It would be better to define a macro for this, for example:

#define DIM 4


Of course, some of the functions in the current implementation can't work with any other matrix. In those functions leave the number 4 as a reminder that you should improve the implementation to support arbitrary dimensions. In other functions that can work with any matrix (with some adjustments) such as
main and fill, replace the number 4 with DIM`.

Code Snippets

#define DIM 4

Context

StackExchange Code Review Q#69233, answer score: 4

Revisions (0)

No revisions yet.