LeetCode Valid Sudoku
2015-07-21 23:45
295 查看
原题链接在这里:https://leetcode.com/problems/valid-sudoku/
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Hide Tags
Hash Table
Hide Similar Problems
(H) Sudoku Solver
这道题基本没有什么快速方法,唯一就是brute force.
先一行一行检查
然后一列一列检查,这里注意外层for loop是j
最后一个一个小方块来检查,关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.
Time Complexity: O(n^2). Space: O(1).
AC Java:
后面跟上Sudoku Solver.
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character
'.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Hide Tags
Hash Table
Hide Similar Problems
(H) Sudoku Solver
这道题基本没有什么快速方法,唯一就是brute force.
先一行一行检查
然后一列一列检查,这里注意外层for loop是j
最后一个一个小方块来检查,关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.
Time Complexity: O(n^2). Space: O(1).
AC Java:
public class Solution { public boolean isValidSudoku(char[][] board) { if(board == null || board.length != 9 || board[0].length != 9){ return false; } HashSet<Character> hs = new HashSet<Character>(); //check each row for(int i = 0; i<board.length; i++){ hs.clear(); for(int j = 0; j<board[0].length; j++){ if(board[i][j] != '.'){ if(!hs.contains(board[i][j])){ hs.add(board[i][j]); }else{ return false; } } } } //check each column for(int j = 0; j<board[0].length; j++){ hs.clear(); for(int i = 0; i<board.length; i++){ if(board[i][j] != '.'){ if(!hs.contains(board[i][j])){ hs.add(board[i][j]); }else{ return false; } } } } //check each subbox for(int box = 0; box<9; box++){ hs.clear(); for(int i = box/3*3; i<box/3*3+3; i++){ for(int j = box%3*3; j<box%3*3+3; j++){ if(board[i][j] != '.'){ if(!hs.contains(board[i][j])){ hs.add(board[i][j]); }else{ return false; } } } } } return true; } }
后面跟上Sudoku Solver.
相关文章推荐
- .Net学习笔记----2015-07-21(C#基础复习07,关键字、访问修饰符)
- GIT入门篇-基本概念与操作
- 关于Map集合的遍历总结
- 一步一步学习网页开发之一
- 设计模式(6) - 创建型模式总结
- Coins
- 红黑树
- PBKDF2加密
- 任务,信号量、邮箱、队列及其区别
- 第63讲Scala中隐式参数与隐式转换的联合使用解析
- 【数据库开发】认识事务
- java 去除url获取值里的BOM
- Snappy压缩
- How to Cite a Patent
- 【求出所有最短路+最小割】【多校第一场】【G题】
- 【求出所有最短路+最小割】【多校第一场】【G题】
- python 使用getopt 获取配置参数
- 今天还行
- 算法时间复杂度
- 如何在Ubuntu中安装R软件