[leetcode]Sudoku Solver

DFS。这种思路清晰的题目,大问题一般出在小地方。

1.当DFS找到时,要返回true。这样一路true上去,否则最后格子又会被设为'.';

2.计算格子所在九宫格时,要用int a = x/3*3+i; 忘记乘3了,一直错;

public class Solution {

    public void solveSudoku(char[][] board) {

        // Start typing your Java solution below

        // DO NOT write main() function

        int m = board.length;

        if (m == 0) return;

        int n = board[0].length;

        if (n == 0) return;       

        

        ArrayList<Point> arr = new ArrayList<Point>();

        

        for (int i = 0; i < m; i++) {

            for (int j = 0; j < n; j++) {

                if (board[i][j] == '.') {

                    Point p = new Point();

                    p.x = i;

                    p.y = j;

                    arr.add(p);

                }

            }

        }

        

        dfs(board, arr, 0);

    }

        

    boolean dfs(char[][] board, ArrayList<Point> arr, int k) {

        if (k == arr.size()) {

            return true;

        }

        else {

            for (int d = 0; d < 9; d++) {

                Point p = arr.get(k);

                board[p.x][p.y] = (char)(d + '1');

                // check valid

                if (IsValid(board, p.x, p.y) && dfs(board, arr, k+1))

                {

                    return true;

                }

                board[p.x][p.y] = '.';                    

            }

        }

        return false;

    }

    

    private boolean IsValid(char[][] board, int x, int y) {

        int len = board.length;

        char c = board[x][y];

        for (int i = 0; i < len; i++) {

            if (x != i && board[i][y] == c) {

                return false;

            }

        }

        

        for (int i = 0; i < len; i++) {

            if (y != i && board[x][i] == c) {

                return false;

            }

        }

        

        for (int i = 0; i < 3; i++) {

            for (int j = 0; j < 3; j++) {

                int a = x/3*3+i;

                int b = y/3*3+j;

                if ((a != x) && (b != y) && board[a][b] == c) {

                    return false;

                }

            }

        }

        return true;

    }

}



class Point {

    public int x;

    public int y;

}

  

你可能感兴趣的:(LeetCode)