Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2015
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <set>
  5.  
  6. const int SIZE = 9;
  7.  
  8. typedef std::vector< std::vector<int> > Matrix;
  9.  
  10. Matrix read_puzzle()
  11. {
  12. Matrix puzzle(SIZE, std::vector<int>(SIZE, 0)); // this line initializes 9x9 board filled with zeros
  13. for (int i = 0; i < SIZE; ++i) {
  14. for (int j = 0; j < SIZE; ++j) {
  15. std::cin >> puzzle[i][j];
  16. }
  17. }
  18. return puzzle;
  19. }
  20.  
  21. void print_puzzle(Matrix puzzle) // a better way to pass a puzzle is pass-by-reference(instead of pass-by-value)
  22. {
  23. for (int i = 0; i < SIZE; ++i) {
  24. for (int j = 0; j < SIZE; ++j) {
  25. std::cout << puzzle[i][j] << " ";
  26. }
  27. std::cout << std::endl;
  28. }
  29.  
  30. }
  31.  
  32. bool is_valid_puzzle(Matrix puzzle, bool zeros_are_valid)
  33. {
  34. std::vector< std::set<int> > rowNums(SIZE, std::set<int>());
  35. std::vector< std::set<int> > colNums(SIZE, std::set<int>());
  36. std::vector< std::set<int> > squareNums(SIZE, std::set<int>());
  37. for (int i = 0; i < SIZE; ++i) {
  38. for (int j = 0; j < SIZE; ++j) {
  39. if (puzzle[i][j] == 0) {
  40. if (!zeros_are_valid) {
  41. return false;
  42. }
  43. continue;
  44. }
  45.  
  46. // TODO remove copypasta
  47. if (!rowNums[i].count(puzzle[i][j])) {
  48. rowNums[i].insert(puzzle[i][j]);
  49. } else {
  50. return false;
  51. }
  52.  
  53. if (!colNums[j].count(puzzle[i][j])) {
  54. colNums[j].insert(puzzle[i][j]);
  55. } else {
  56. return false;
  57. }
  58.  
  59. if (!squareNums[(i/3)*3 + (j/3)].count(puzzle[i][j])) {
  60. squareNums[(i/3)*3 + (j/3)].insert(puzzle[i][j]);
  61. } else {
  62. return false;
  63. }
  64. }
  65. }
  66. // debug output
  67. std::cout << "DEBUG" << std::endl;
  68. print_puzzle(puzzle);
  69. std::cout << "/DEBUG" << std::endl;
  70. return true;
  71. }
  72.  
  73. Matrix solve_puzzle(Matrix puzzle)
  74. {
  75. for (int i = 0; i < SIZE; ++i) {
  76. for (int j = 0; j < SIZE; ++j) {
  77. if (puzzle[i][j] == 0) {
  78. for (int candidate_number = 1; candidate_number <= SIZE; ++candidate_number) {
  79. puzzle[i][j] = candidate_number;
  80. if (is_valid_puzzle(puzzle, true)) {
  81. Matrix candidate_puzzle = solve_puzzle(puzzle);
  82. if (is_valid_puzzle(candidate_puzzle, false)) {
  83. return candidate_puzzle;
  84. }
  85. }
  86. }
  87. }
  88. }
  89. }
  90. return puzzle;
  91. }
  92.  
  93. int main()
  94. {
  95. Matrix puzzle = read_puzzle();
  96. print_puzzle(puzzle);
  97. Matrix solved_puzzle = solve_puzzle(puzzle);
  98. std::cout << "~~~~~~~~~~~~" << std::endl;
  99. print_puzzle(solved_puzzle);
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement