summaryrefslogtreecommitdiff
path: root/solver.c
blob: b6de45ed3d2695f64bbf9f27ba65530a73f3ea5a (plain)
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
#include <stdio.h>
#include <string.h>

#include "debug.h"
#include "update.h"
#include "cell.h"
#include "solve.h"
#include "display.h"
#include "load.h"

int solve(struct cell (*board)[9][9])
{
	int i = 0;
	int total_changes = 0;
	int change_count = -1;
	/* 9*9 is worst case */
	for (i = 0; i < 9*9 && change_count; i++) {
		change_count = 0;
		update_not_row_col(board);
		change_count += not_to_val_cell(board);
		change_count += solve_row_col(board);
		change_count += cells_fill_certainties(board);
		total_changes += change_count;
//		display(board);
	}
	return total_changes;
}

int main(int argc, char **argv)
{
	int total_changes = 0;
	struct cell board[9][9];
	FILE *f = NULL;

	memset(board, 0, sizeof(board));

	if (argc != 2) {
		printf("Syntax: %s puzzle_file\n", argv[0]);
		return 1;
	}

	f = fopen(argv[1], "r");
	if (!f) {
		perror("fopen");
		return 1;
	}

	if (load(f, &board) < 0) {
		fclose(f);
		return 1;
	}

	fclose(f);

	display(board);
	total_changes = solve(&board);

	if (board_is_solved(&board) < 0) {
		printf("Could not solve the board! Here is the closest (%d changes)\n", total_changes);
	} else {
		printf("Solution (%d changes)\n", total_changes);
	}
	display(board);

}