diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index ccde36383..d631d5dfd 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -59,14 +59,19 @@ namespace backtracking { * Utility function to print matrix * @tparam V number of vertices in array * @param mat matrix where numbers are saved + * @param starting_mat copy of mat, required by printMat for highlighting the differences * @param n number of times loop will run * @return void */ template - void printMat(const std::array , V> &mat, int n) { + void printMat(const std::array , V> &mat, const std::array , V> &starting_mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - std::cout << mat[i][j] << " "; + if (starting_mat[i][j] != mat[i][j]) { + std::cout << "\033[93m" << mat[i][j] << "\033[0m" << " "; + } else { + std::cout << mat[i][j] << " "; + } if ((j + 1) % 3 == 0) { std::cout << '\t'; } @@ -82,28 +87,29 @@ namespace backtracking { * Sudoku algorithm * @tparam V number of vertices in array * @param mat matrix where numbers are saved + * @param starting_mat copy of mat, required by printMat for highlighting the differences * @param i current index in rows * @param j current index in columns * @returns `true` if 'no' was placed * @returns `false` if 'no' was not placed */ template - bool solveSudoku(std::array , V> &mat, int i, int j) { + bool solveSudoku(std::array , V> &mat, const std::array , V> &starting_mat, int i, int j) { /// Base Case if (i == 9) { /// Solved for 9 rows already - backtracking::printMat(mat, 9); + backtracking::printMat(mat, starting_mat, 9); return true; } /// Crossed the last Cell in the row if (j == 9) { - return backtracking::solveSudoku(mat, i + 1, 0); + return backtracking::solveSudoku(mat, starting_mat, i + 1, 0); } /// Blue Cell - Skip if (mat[i][j] != 0) { - return backtracking::solveSudoku(mat, i, j + 1); + return backtracking::solveSudoku(mat, starting_mat, i, j + 1); } /// White Cell /// Try to place every possible no @@ -111,7 +117,7 @@ namespace backtracking { if (backtracking::isPossible(mat, i, j, no, 9)) { /// Place the 'no' - assuming a solution will exist mat[i][j] = no; - bool solution_found = backtracking::solveSudoku(mat, i, j + 1); + bool solution_found = backtracking::solveSudoku(mat, starting_mat, i, j + 1); if (solution_found) { return true; } @@ -142,9 +148,10 @@ int main() { std::array {0, 0, 0, 0, 8, 0, 0, 7, 9} }; - backtracking::printMat(mat, 9); + backtracking::printMat(mat, mat, 9); std::cout << "Solution " << std::endl; - backtracking::solveSudoku(mat, 0, 0); + std::array , V> starting_mat = mat; + backtracking::solveSudoku(mat, starting_mat, 0, 0); return 0; }