#36 Valid Sudoku
2015-06-02 20:12
295 查看
题目:
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
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
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.
题解:
Note中写到,本题对Valid Sudoku的定义是行,列,3×3子格不能有重复数字,而不是一定有解。
思路也就很清楚了,依次判断即可。
用List.IndexOf获得值的索引并比较以判断是否有重复,很好的思路(原谅我少见多怪吧~~)。
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
'.'.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
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.
题解:
Note中写到,本题对Valid Sudoku的定义是行,列,3×3子格不能有重复数字,而不是一定有解。
思路也就很清楚了,依次判断即可。
public class Solution { public boolean isValidSudoku(char[][] board) { for(int i=0;i<9;i++){ //判断列 List<Character> list = new ArrayList<Character>(); for(int j=0;j<9;j++){ list.add(board[j][i]); } if(!isValid(list)){ return false; } //判断行 list = new ArrayList<Character>(); for(int j=0;j<9;j++){ list.add(board[i][j]); } if(!isValid(list)){ return false; } } //判断3×子格 for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ List<Character> list = new ArrayList<Character>(); for(int k=0;k<3;k++){ for(int l=0;l<3;l++){ list.add(board[i*3+k][j*3+l]); } } if(!isValid(list)) return false; } } return true; } private boolean isValid(List<Character> list){ for(Character ch : list){ if(ch != '.') if(list.indexOf(ch) != list.lastIndexOf(ch))//List.IndexOf处理重复 return false; } return true; } }注:List.IndexOf返回List或它的一部分中某个值的第一个匹配项的从零开始的索引,List.IndexOf (T, Int32, Int32)。
用List.IndexOf获得值的索引并比较以判断是否有重复,很好的思路(原谅我少见多怪吧~~)。
相关文章推荐
- Nginx+Tomcat负载均衡配置
- HDU 1081 To The Max
- 教你从redhat官网获取ISO镜像
- 二分法查找
- NEUQ 1397: 重建长城卷土重来
- node模块函数图解
- 【Hibernate学习笔记-6.1】无连接表的N-1关联(单向)
- leetcode_Number of 1 Bits_easy
- 面试题:使用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变?
- 分布式MySQL数据库TDSQL架构分析
- 凯云水利水电工程造价管理系统 技术解析(八) 机械单价(三)
- 003_01JavaScript之基础简介
- iOS-学习笔记-UI-第一天
- Centos6安装Qt5版本
- edx安装
- 欢迎使用CSDN-markdown编辑器
- response
- 会员卡管理系统技术解析(十)添加会员挂失恢复记录
- 8.16编写一个函数模板,使用冒泡法将数组内容从小排列到大
- Software-artifact Infrastructure Repository 学习笔记 2:C Object Handbooky