码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Valid Sudoku

时间:2014-11-12 17:55:20      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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 ‘.‘.

bubuko.com,布布扣

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.

原题链接:https://oj.leetcode.com/problems/valid-sudoku/

按照数独的规则,一行、一列、对角线、9个小格中不出现同一个数字。

import java.util.ArrayList;
import java.util.List;


public class ValidSudoku {
	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[i][j]);
			if(!isValid(list))
				return false;
		}
		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;
		}
		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))
					return false;
		}
		return true;
	}
}


LeetCode——Valid Sudoku

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/41045195

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!