From 536cb5922f4c8cd1db7e1707ba797201c8267e1f Mon Sep 17 00:00:00 2001 From: David Phillips Date: Sun, 10 Mar 2019 21:58:20 +1300 Subject: Implement board solving check --- solve.c | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 97 insertions(+), 5 deletions(-) diff --git a/solve.c b/solve.c index 0a1cb69..d9bc01d 100644 --- a/solve.c +++ b/solve.c @@ -219,25 +219,117 @@ int board_is_filled(struct cell (*b)[9][9]) return 0; } +/* + * Check if all of the rows on are correctly solved on a board + * Returns 0 for all rows correctly solved + */ int board_rows_are_solved(struct cell (*b)[9][9]) { - return -1; + int row_has[9] = {0}; + int val = 0; + int x = 0; + int y = 0; + + for (y = 0; y < 9; y++) { + memset(row_has, 0, sizeof(row_has)); + for (x = 0; x < 9; x++) { + val = (*b)[x][y].val; + if (val == 0) { + return -1; + } + if (row_has[val - 1]) { + DEBUG_LOG("Invalid board: Row %d duplicate %d\n", y, val); + return -1; + } + row_has[val - 1] = 1; + } + } + + return 0; } +/* + * Check if all of the columns on are correctly solved on a board + * Returns 0 for all columns correctly solved + */ int board_cols_are_solved(struct cell (*b)[9][9]) { - return -1; + int col_has[9] = {0}; + int val = 0; + int x = 0; + int y = 0; + + for (x = 0; x < 9; x++) { + memset(col_has, 0, sizeof(col_has)); + for (y = 0; y < 9; y++) { + val = (*b)[x][y].val; + if (val == 0) { + return -1; + } + if (col_has[val - 1]) { + DEBUG_LOG("Invalid board: Column %d duplicate %d\n", x, val); + return -1; + } + col_has[val - 1] = 1; + } + } + + return 0; } +/* + * Check if one of the nine 3x3 blocks is correctly solved on a board + * Returns 0 for a correctly solved 3x3 + */ +int board_3_is_solved(struct cell (*b)[9][9], int cx, int cy) +{ + int col_has[9] = {0}; + int val = 0; + int x = 0; + int y = 0; + + cx *= 3; + cy *= 3; + + for (x = cx; x < cx + 3; x++) { + for (y = cy; y < cy + 3; y++) { + val = (*b)[x][y].val; + if (val == 0) { + return -1; + } + if (col_has[val - 1]) { + DEBUG_LOG("Invalid board: 3x3 %d duplicate %d\n", x, val); + return -1; + } + col_has[val - 1] = 1; + } + } + + return 0; +} + +/* + * Check if all of the nine 3x3 blocks are correctly solved on a board + * Returns 0 for correctly solved 3x3s + */ int board_3s_are_solved(struct cell (*b)[9][9]) { - return -1; + int ret = 0; + int x = 0; + int y = 0; + for (x = 0; x < 3; x++) { + for (y = 0; y < 3; y++) { + ret = board_3_is_solved(b, x, y); + if (ret) + return ret; + } + } + return ret; } /* * Check if a board is solved. - * Returns -1 isf the board is unsolved - * Returns 0 if the board is solved + * Returns 0 if the board is solved correctly */ int board_is_solved(struct cell (*b)[9][9]) { -- cgit v1.1