Java for LeetCode 037 Sudoku Solver
2015-05-08 20:02
531 查看
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.
解题思路:
经典的NP问题,采用
本题方法多多,优化算法也是多多,本例仅给出最简单的DFS暴力枚举算法。
JAVA实现如下:
Empty cells are indicated by the character
'.'.
You may assume that there will be only one unique solution.
解题思路:
经典的NP问题,采用
Dancing Links可以优化算法,参考链接:https://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/sudoku.paper.html
本题方法多多,优化算法也是多多,本例仅给出最简单的DFS暴力枚举算法。
JAVA实现如下:
static public void solveSudoku(char[][] board) { int count = 0; for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) if (board[i][j] == '.') count++; dfs(board, count); } public static int dfs(char[][] board, int count) { if (count == 0) return 0; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == '.') { for (int k = 1; k <= 10; k++) { if (k == 10) return count; board[i][j] = (char) ('0' + k); if (!isValid(board, i, j)) board[i][j] = '.'; else { count--; count = dfs(board, count); if (count == 0) return count; count++; board[i][j] = '.'; } } } } } return count; } static public boolean isValid(char[][] board, int row, int col) { HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>(); for (int j = 0; j < board[0].length; j++) { if (board[row][j] != '.') { if (hashmap.containsKey(board[row][j])) return false; hashmap.put(board[row][j], 1); } } hashmap = new HashMap<Character, Integer>(); for (int i = 0; i < board.length; i++) { if (board[i][col] != '.') { if (hashmap.containsKey(board[i][col])) return false; hashmap.put(board[i][col], 1); } } hashmap = new HashMap<Character, Integer>(); int rowTemp = (row / 3) * 3; int colTemp = (col / 3) * 3; for (int k = 0; k < 9; k++) { if (board[rowTemp + k / 3][colTemp + k % 3] != '.') { if (hashmap .containsKey(board[rowTemp + k / 3][colTemp + k % 3])) return false; hashmap.put(board[rowTemp + k / 3][colTemp + k % 3], 1); } } return true; }
相关文章推荐
- Java for LeetCode 218 The Skyline Problem【HARD】
- Java for LeetCode 233 Number of Digit One
- Java for LeetCode 035 Search Insert Position
- Java for LeetCode 129 Sum Root to Leaf Numbers
- Java for LeetCode 136 Single Number
- Java for LeetCode 043 Multiply Strings
- Java for LeetCode 147 Insertion Sort List
- Java for LeetCode 149 Max Points on a Line
- Java for LeetCode 026 Remove Duplicates from Sorted Array
- Java for LeetCode 029 Divide Two Integers
- LeetCode 34 Search for a Range (C,C++,Java,Python)
- Java for LeetCode 050 Pow(x, n)
- Java for LeetCode 054 Spiral Matrix
- Java for LeetCode 202 Happy Number
- Java for LeetCode 230 Kth Smallest Element in a BST
- Java for LeetCode 072 Edit Distance【HARD】
- Java for LeetCode 219 Contains Duplicate II
- leetcode 037 —— Sudoku Solver
- Java for LeetCode 235 Lowest Common Ancestor of a Binary Search Tree
- Java for LeetCode 224 Basic Calculator