LeetCode 笔记系列十 Suduko
2013-07-07 18:27
731 查看
题目: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.
下面是一个数独的题目:
View Code
注意我们对3x3格的标号方式,是从左到右从上到下,标号为0~8,方便我们转换。
这道题虽然不难,但是比较经典,值得总结。
Empty cells are indicated by the character
'.'.
You may assume that there will be only one unique solution.
下面是一个数独的题目:
/** * 决定board[row][col]可填写的数字 * @param board * @param row * @param col * @param set 当函数返回时,set[i]为false表明数字i+1可以填写到棋盘中。 * @return */ private static boolean[] scanColRowGrid(char[][] board, int row, int col, boolean[] set){ for(int i = 0; i < SIZE; i++){ if(board[row][i] >= '1' && board[row][i] <= '9') { set[board[row][i] - '1'] = true; } } for(int i = 0; i < SIZE; i++){ if(board[i][col] >= '1' && board[i][col] <= '9') { set[board[i][col] - '1'] = true; } } int grid = getGrid(row, col); int st_row = 3 * (grid / 3); int st_col = 3 * (grid % 3); for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ char c = board[st_row + i][st_col + j]; if(c >= '1' && c <= '9') { set[c - '1'] = true; } } } return set; } /** * 通过行号和列号查询该格子所在的3x3格 * @param row * @param col * @return 0~8的数字,代表从左到右从上到下的3x3格标号 */ private static int getGrid(int row, int col){ return 3 * (row / 3) + col / 3; }
View Code
注意我们对3x3格的标号方式,是从左到右从上到下,标号为0~8,方便我们转换。
这道题虽然不难,但是比较经典,值得总结。
相关文章推荐
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
- LeetCode 笔记系列一 Median of Two Sorted Arrays
- LeetCode 笔记系列三 3Sum
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
- LeetCode 笔记系列 14 N-Queen II [思考的深度问题]
- LeetCode 笔记系列七 Substring with Concatenation of All Words
- leetcode解题笔记:Two sum系列解题思路
- LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
- leetcode笔记--Best Time to Buy and Sell Stock系列(I,II, III, IV)
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用](最大矩形)
- LeetCode 笔记系列二 Container With Most Water
- LeetCode 笔记系列11 First Missing Positive [为什么我们需要insight]
- LeetCode 笔记系列四 Remove Nth Node From End of List
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
- LeetCode 笔记系列五 Generate Parentheses
- LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]