leetcode--Sudoku Solver

來源:互聯網
上載者:User

標籤:blog   http   java   art   for   io   

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.

 

This is a simple problem on dfs method

public class Solution {    public void solveSudoku(char[][] board){        List<Integer> blankCells = new ArrayList<Integer>();//a sudoku board is a 9 by 9 arrayfor(int i = 0; i < 81; ++i){    if(board[i / 9][ i % 9 ] == ‘.‘)blankCells.add(i);}dfs(board, 0, blankCells);    }private boolean dfs(char[][] board, int start, List<Integer> blankCells) {if(start == blankCells.size()) return true; //dfs reaches the end//get the coordinates of the cell to be filledint currentCoordinate = blankCells.get(start);int row = currentCoordinate / 9;int column = currentCoordinate % 9;//fill a number in the cellfor(int num = 1; num < 10; ++num) {//check the sudoku is valid after being filled numif(isValid(num, board,row,column)) {board[row][column] = (char)(num + ‘0‘);if(dfs(board,start + 1, blankCells))return true;//if a solution can not be reached after the filling, we need to erase the filling for next tryboard[row][column] = ‘.‘;}}return false;}private boolean isValid(int num, char[][] board, int row, int column) {//check whether num is in the row, column and gridfor(int i = 0; i < 9; ++i){if(board[row][i] -‘0‘ == num) return false; //row if(board[i][column] - ‘0‘ == num) return false; //columnif(board[3 *(row / 3) + i / 3][3 * (column / 3) + i % 3] - ‘0‘ == num) return false;}return true;    }}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.