Problem
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ".".
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
The given board contain only digits 1-9 and the character ".".
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.
class Solution { public void solveSudoku(char[][] board) { if (board == null || board.length == 0) return; solve(board); } private boolean solve(char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == ".") { for (char ch = "1"; ch <= "9"; ch++) { if (isValid(board, i, j, ch)) { board[i][j] = ch; if (solve(board)) return true; else board[i][j] = "."; } } return false; } } } return true; } private boolean isValid(char[][] board, int row, int col, char ch) { for (int i = 0; i < 9; i++) { if (board[i][col] == ch) return false; if (board[row][i] == ch) return false; if (board[row/3*3+i/3][col/3*3+i%3] == ch) return false; } return true; } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://systransis.cn/yun/77247.html
摘要:題目要求也就是給出一個解決數(shù)獨的方法,假設每個數(shù)獨只有一個解決方案。并將當前的假象結果帶入下一輪的遍歷之中。如果最終遍歷失敗,則逐級返回,恢復上一輪遍歷的狀態(tài),并填入下一個合理的假想值后繼續(xù)遍歷。 題目要求 Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indi...
摘要:的可以由確定,這一點在里面的位置可以由確定所以每確定一行,每一個值都可以被轉換到一個之中。如果允許的空間復雜度,可以設置一個二維數(shù)組來用來判斷是否在里重現(xiàn)了重復的數(shù)字。將一個數(shù)字的每一個位上表示每一個數(shù)字。 Leetcode[36] Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - ...
摘要:如果重復則不合法,否則極為合法。在這里我們使用數(shù)組代替作為存儲行列和小正方形的值得數(shù)據(jù)結構。我存儲這所有的行列小正方形的情況,并判斷當前值是否重復。外循環(huán)則代表對下一行,下一列和下一個小正方形的遍歷。 題目要求 Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku boa...
摘要:要求我們判斷已經(jīng)填入的數(shù)字是否滿足數(shù)獨的規(guī)則。即滿足每一行每一列每一個粗線宮內(nèi)的數(shù)字均含,不重復。沒有數(shù)字的格子用字符表示。通過兩層循環(huán)可以方便的檢查每一行和每一列有沒有重復數(shù)字。對于每個,作為縱坐標,作為橫坐標。 題目詳情 Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.The Sudo...
摘要:每天會折騰一道及以上題目,并將其解題思路記錄成文章,發(fā)布到和微信公眾號上。三匯總返回目錄在月日月日這半個月中,做了匯總了數(shù)組知識點?;蛘呃奖疚淖钕旅妫砑拥奈⑿诺葧鶕?jù)題解以及留言內(nèi)容,進行補充,并添加上提供題解的小伙伴的昵稱和地址。 LeetCode 匯總 - 2019/08/15 Create by jsliang on 2019-08-12 19:39:34 Recently...
閱讀 3979·2021-11-24 09:38
閱讀 1243·2021-10-19 11:42
閱讀 1840·2021-10-14 09:42
閱讀 2166·2019-08-30 15:44
閱讀 555·2019-08-30 14:04
閱讀 2901·2019-08-30 13:13
閱讀 1963·2019-08-30 12:51
閱讀 972·2019-08-30 11:22