首页 > 学院 > 开发设计 > 正文

leetcode - 37.Sudoku Solver

2019-11-06 07:49:51
字体:
来源:转载
供稿:网友

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.

Sudoku-1

A sudoku puzzle…

Sudoku-2

…and its solution numbers marked in red.

Solution:

public void solveSudoku(char[][] board) { solve(board); } private boolean solve(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; 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 row, int col, char c) { for (int i = 0; i < 9; i++) { if (board[row][i] != '.' && board[row][i] == c) { return false; } if (board[i][col] != '.' && board[i][col] == c) { return false; } int rowIndex = (row / 3) * 3 + i / 3; int columnIndex = (col / 3) * 3 + i % 3; if (board[rowIndex][columnIndex] != '.' && board[rowIndex][columnIndex] == c) { return false; } } return true; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表