File tree Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Original file line number Diff line number Diff line change 10
10
11
11
## How it works
12
12
13
+ ### Sudoku board detection
13
14
15
+ To identify the sudoku board the input image is processed as follows with [ OpenCV] ( https://github.com/opencv/opencv ) :
16
+ - Using the Canny algorithm to detect all contours in the image.
17
+ - The biggest contour corresponds to the whole sudoku puzzle.
18
+ - Use the found contour to extract and warp the sudoku grid .
14
19
15
- <img src =" demo/demo1.gif " width =100% ></img >
20
+ The numbers are detected using [ MLKit Text Recognition] ( https://developers.google.com/ml-kit/vision/text-recognition/v2 ) .
21
+
22
+ <br >
23
+
24
+ <p align =" center " >
25
+ <img src =" demo/demo1.gif " ></img >
26
+ </p >
27
+
28
+ <br >
29
+
30
+ ### Solving
31
+ For solving the puzzle I'm using a fairly simple, brute-force algorithm that relies on backtracking to generate the valid solution.
32
+ <br >
33
+ It goes through the whole 2D array and for each number that needs to be found it tries all possibilities and continues with the following numbers.
34
+ <br >
35
+ <br >
36
+ For each cell there are 9 possible numbers which means the time complexity of this algorithm is O(9<sup >N</sup >).
37
+
38
+ ```
39
+ private fun solve(index: Int = 0): Boolean {
40
+ for (i in index until 81) {
41
+ val r = i / 9
42
+ val c = i % 9
43
+ if (sudokuBoard[r][c].number == 0) {
44
+ for (n in 1..9) {
45
+ if (isValidSolution(r, c, n)) {
46
+ sudokuBoard[r][c].number = n
47
+ if (solve(i + 1)) {
48
+ return true
49
+ }
50
+ sudokuBoard[r][c].number = 0
51
+ }
52
+ }
53
+ return false
54
+ }
55
+ }
56
+ return true
57
+ }
58
+ ```
59
+ <br >
60
+ <p align =" center " >
61
+ <img src =" demo/demo2.gif " ></img >
62
+ </p >
63
+ <p align =" center " >
64
+ <span >Solve algorithm demo</span >
65
+ </p >
16
66
17
67
## Getting Started
You can’t perform that action at this time.
0 commit comments