File tree Expand file tree Collapse file tree 3 files changed +131
-0
lines changed
Expand file tree Collapse file tree 3 files changed +131
-0
lines changed Original file line number Diff line number Diff line change 1+ def main
2+
3+ var board is int[9][9]
4+
5+ def printBoard: b as int[][9]
6+ var i j is int
7+ i := 0
8+ loop:
9+ if i < 9:
10+ j := 0
11+ loop:
12+ if j < 9:
13+ writeInteger: b[i][j]
14+ if j < 8: writeString: " "
15+ j := j + 1
16+ else: break
17+ writeString: "\n"
18+ i := i + 1
19+ else: break
20+
21+ def isSafe is byte: b as int[][9], row col num as int
22+ var i j boxStartRow boxStartCol is int
23+
24+ # Row check
25+ j := 0
26+ loop:
27+ if j < 9:
28+ if b[row][j] = num: return: false
29+ j := j + 1
30+ else: break
31+
32+ # Column check
33+ i := 0
34+ loop:
35+ if i < 9:
36+ if b[i][col] = num: return: false
37+ i := i + 1
38+ else: break
39+
40+ # 3x3 box check
41+ boxStartRow := (row / 3) * 3
42+ boxStartCol := (col / 3) * 3
43+ i := 0
44+ loop:
45+ if i < 3:
46+ j := 0
47+ loop:
48+ if j < 3:
49+ if b[boxStartRow + i][boxStartCol + j] = num: return: false
50+ j := j + 1
51+ else: break
52+ i := i + 1
53+ else: break
54+
55+ return: true
56+
57+ def findEmpty is byte: b as int[][9], rowRef colRef as ref int
58+ var i j is int
59+ i := 0
60+ loop:
61+ if i < 9:
62+ j := 0
63+ loop:
64+ if j < 9:
65+ if b[i][j] = 0:
66+ rowRef := i
67+ colRef := j
68+ return: true
69+ j := j + 1
70+ else: break
71+ i := i + 1
72+ else: break
73+ return: false
74+
75+ def solve is byte: b as int[][9]
76+ var row col num is int
77+ var hasEmpty is byte
78+
79+ hasEmpty := findEmpty(b, row, col)
80+ if hasEmpty = false:
81+ return: true
82+
83+ num := 1
84+ loop:
85+ if num <= 9:
86+ if isSafe(b, row, col, num):
87+ b[row][col] := num
88+ if solve(b):
89+ return: true
90+ b[row][col] := 0 # backtrack
91+ num := num + 1
92+ else: break
93+
94+ return: false
95+
96+ # Read 9x9 grid (0 = empty)
97+ var i j is int
98+ i := 0
99+ loop:
100+ if i < 9:
101+ j := 0
102+ loop:
103+ if j < 9:
104+ board[i][j] := readInteger()
105+ j := j + 1
106+ else: break
107+ i := i + 1
108+ else: break
109+
110+ if solve(board):
111+ printBoard: board
112+ else:
113+ writeString: "No solution\n"
Original file line number Diff line number Diff line change 1+ 5 3 0 0 7 0 0 0 0
2+ 6 0 0 1 9 5 0 0 0
3+ 0 9 8 0 0 0 0 6 0
4+ 8 0 0 0 6 0 0 0 3
5+ 4 0 0 8 0 3 0 0 1
6+ 7 0 0 0 2 0 0 0 6
7+ 0 6 0 0 0 0 2 8 0
8+ 0 0 0 4 1 9 0 0 5
9+ 0 0 0 0 8 0 0 7 9
Original file line number Diff line number Diff line change 1+ 5 3 4 6 7 8 9 1 2
2+ 6 7 2 1 9 5 3 4 8
3+ 1 9 8 3 4 2 5 6 7
4+ 8 5 9 7 6 1 4 2 3
5+ 4 2 6 8 5 3 7 9 1
6+ 7 1 3 9 2 4 8 5 6
7+ 9 6 1 5 3 7 2 8 4
8+ 2 8 7 4 1 9 6 3 5
9+ 3 4 5 2 8 6 1 7 9
You can’t perform that action at this time.
0 commit comments