Solve Wordoku in C with Recursion

  • Thread starter Thread starter wannawin
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 5K views
wannawin
Messages
14
Reaction score
0

Homework Statement



I'm fairly new to programming and I'm trying to write a program in C to solve wordoku (sudoku with letters) problems recursively, but I seem to be having some trouble with the recursion part of it.

The user enters in a string of characters which will make up the 9 allowable characters in the game. They then enter the 9 lines of the given puzzle, placing "#' in any blank spaces. In the end the solution is printed.

The Attempt at a Solution


Here is what I have done.
Code:
#include <stdio.h>
#include <stdlib.h>
bool chkRow(int i, int j, char c, char puzzle[][10])
{
	for(;j<9;j++)
		if(c==puzzle[i][j])
			return false;
	return true;
}

bool chkColumn(int i, int j, char c, char puzzle[][10])
{
	for(;i<9;i++)
		if(c==puzzle[i][j])
			return false;
	return true;
}

bool chkCell(int i, int j, char c, char puzzle[][10])
{
	int x=i-(i%3);
	int y=j-(j%3);
	for(i=x;i<x+3;i++)
		for(j=y;j<y+3;j++)
			if(c==puzzle[i][j])
				return false;
	return true;
}

void solver(char charBank[10], char puzzle[][10], int i, int j, int k)
{
	if(puzzle[i][j]=='#')	
	{
		char c=charBank[k];		

		if(i==9)
			for(i=0;i<9;i++)
			{
				printf("%s\n",puzzle[i]);	
			}
		if(chkRow(i, j, c, puzzle)
		&&chkColumn(i, j, c, puzzle)
		&&chkCell(i, j, c, puzzle))
		{
			puzzle[i][j]=c;
			if(j==8)
				solver(charBank, puzzle, i+1, 0, 0);
			else
				solver(charBank, puzzle, i, j+1, 0);	
		}
		else				
			solver(charBank, puzzle, i, j, k+1);
	}
	else if(j==8)
		solver(charBank, puzzle, i+1, 0, 0);
	else
		solver(charBank, puzzle, i, j+1, 0);
}

int main(void)
{
	int i=0,j=0,k=0;
	
	char charBank[10];
	gets(charBank);
	
	char puzzle[9][10];
	for(i=0;i<9;i++)
		gets(puzzle[i]);             
	printf("\n");
	                                 
	solver(charBank, puzzle, 0, 0, 0);
	return 0;
}
 
Physics news on Phys.org
Lab 7, eh.

Please don't post your code for Labs online. You're giving anybody the chance to copy it, and posting it online is an academic offence. If I were you, I'd delete the code from here and try working at it again.

Losing 3 % of your mark isn't a big deal, losing 3 % of your mark AND getting an getting an academic offence is.