Sudoku Solver

来源:互联网 发布:人工智能工程师 编辑:程序博客网 时间:2024/06/08 10:58

rite 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.

思路: 典型的回溯法, 和 N-QUEENS 问题一样。 但是为了方便进行下一轮递归, 将所有为空的点的位置存入一个list ,这样方便递归和判断是否结束。

易错点: 在每个block 的判断是否正确时, i 从 0 到 9  刚好在一个block 中。            

 int blockRow = 3 * (x / 3) + i / 3;
            int blockCol = 3 * (y / 3) + i % 3;
            if(board[blockRow][blockCol] == c)
                return false;

public class Solution {    public void solveSudoku(char[][] board) {        List<Integer> emptyNodes = new ArrayList<Integer>();        for(int i = 0; i < 9; i++){            for(int j = 0; j < 9; j++){                if(board[i][j] == '.'){                    emptyNodes.add(i * 9 + j);                }            }        }        dfs(board, 0, emptyNodes);    }        private boolean dfs(char[][] board, int cur, List<Integer> emptyNodes){        if(cur == emptyNodes.size())            return true;        int node = emptyNodes.get(cur);        int x = node / 9;        int y = node % 9;        for(char c = '1'; c <='9'; c++){            if(isValid(board, x, y, c)){                board[x][y] = c;                if(dfs(board, cur + 1, emptyNodes))                    return true;                board[x][y] = '.';            }        }        return false;    }        private boolean isValid(char[][] board, int x, int y, char c){        for(int i = 0; i < 9; i++){            if(board[x][i] == c)                return false;            if(board[i][y] == c)                return false;            int blockRow = 3 * (x / 3) + i / 3;            int blockCol = 3 * (y / 3) + i % 3;            if(board[blockRow][blockCol] == c)                return false;        }        return true;    }}


0 0
原创粉丝点击