Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

A sudoku puzzle...

...and its solution numbers marked in red.

https://leetcode.com/problems/sudoku-solver/

Solution :

https://leetcode.com/discuss/9929/a-java-solution-with-notes

public class Solution { public void solveSudoku(char[][] board) { if (board.length == 0) { return; } solve(board); } public boolean solve(char[][] board) { int m = board.length; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { if (board[i][j] == '.') { for (char c = '1'; c <= '9'; c++) { if (isValid(board, i, j, c)) { board[i][j] = c; if (solve(board)) { return true; } else { board[i][j] = '.'; } } } return false; } } } return true; } public boolean isValid(char[][] board, int i, int j, char c) { // check col for (int row = 0; row < board.length; row++) { if (board[row][j] == c) { return false; } } // check row for (int col = 0; col < board.length; col++) { if (board[i][col] == c) { return false; } } // check block for (int row = (i/3)3; row < (i/3)3+3; row++) { for (int col = (j/3)3; col < (j/3)3+3; col++) { if (board[row][col] == c) { return false; } } } return true; } }

results matching ""

    No results matching ""