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

Leetcode Valid Sudoku

时间:2015-10-10 06:44:54      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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.


解题思路:

首先检查是否是9*9 矩阵;

其次依次检查每行,每列和内部各个3*3 矩阵是否满足要求。

建立int[] temp, temp.length = 9 来存储1-9 的个数,当temp[i] > 1时,说明有重复数字出现,返回false.


Java code:

public class Solution {
    public boolean isValidSudoku(char[][] board) {
       if(board == null || board.length !=9 || board[0].length != 9){
           return false;
       }
       //check each row
       for(int i = 0; i < 9; i++){
           int[] temp = new int[9];
           for(int j = 0; j < 9; j++){
               if(board[i][j] != ‘.‘){
                   temp[board[i][j] - ‘1‘]++;
                   if(temp[board[i][j] - ‘1‘] > 1){
                       return false;
                   }
               }
           }
       }
       //check each column
       for(int j = 0; j < 9; j++){
           int[] temp = new int[9];
           for(int i = 0; i < 9; i++){
               if(board[i][j] != ‘.‘){
                   temp[board[i][j] - ‘1‘]++;
                   if(temp[board[i][j] - ‘1‘] > 1){
                       return false;
                   }
               }
           }
       }
       //check each 3*3 matrix
       for(int i = 0; i < 3; i++) {
           for(int j = 0; j < 3; j++){
               int[] temp = new int[9];
               for(int m = 3*i; m < 3+3*i; m++){
                   for(int n = 3*j; n < 3+3*j; n++) {
                       if(board[m][n] != ‘.‘){
                           temp[board[m][n] - ‘1‘]++;
                           if(temp[board[m][n] - ‘1‘] > 1){
                               return false;
                           }
                       }
                   }
               }
           }
       }
       return true;
    }
}

Reference:

1. https://leetcode.com/discuss/52006/simple-java-solution-using-three-iterations-all-three-cases

 

Leetcode Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4865634.html

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