Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Sudoku Implementation [✅] - Shuai Zhu #148

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions sudoku.go
Original file line number Diff line number Diff line change
@@ -1 +1,78 @@
package main

import (
"fmt"
)

const N = 9

// SolveSudoku solves the Sudoku puzzle
func SolveSudoku(grid [][]int) [][]int {
if solveSudokuHelper(grid) {
return grid
}
return nil //if the puzzle is unsolvable
}

// solveSudokuHelper is a helper function uses backtracking
func solveSudokuHelper(grid [][]int) bool {
row, col := findEmptyCell(grid)
if row == -1 && col == -1 {
return true // Puzzle solved
}

for num := 1; num <= N; num++ {
if isValid(grid, row, col, num) {
grid[row][col] = num
if solveSudokuHelper(grid) {
return true
}
grid[row][col] = 0 // Backtrack
}
}
return false
}

// findEmptyCell returns the row and column of an empty cell
func findEmptyCell(grid [][]int) (int, int) {
for row := 0; row < N; row++ {
for col := 0; col < N; col++ {
if grid[row][col] == 0 {
return row, col
}
}
}
return -1, -1
}

// isValid checks if a number can be placed in the given cell
func isValid(grid [][]int, row, col, num int) bool {
// Check row and column
for i := 0; i < N; i++ {
if grid[row][i] == num || grid[i][col] == num {
return false
}
}

// Check 3x3 sub-grid
startRow := row - row%3
startCol := col - col%3
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if grid[i+startRow][j+startCol] == num {
return false
}
}
}
return true
}

// printGrid prints the Sudoku grid
func printGrid(grid [][]int) {
for _, row := range grid {
for _, val := range row {
fmt.Printf("%d ", val)
}
fmt.Println()
}
}
Loading