【LeetCode】Valid Sudoku

来源:互联网 发布:kettle java脚本 编辑:程序博客网 时间:2024/05/18 16:38

Valid Sudoku 

Total Accepted: 25228 Total Submissions: 92921 My Submissions Question Solution 
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个小格子,每个格子中有没有重复的数据。

Java AC

public class Solution {    public boolean isValidSudoku(char[][] board) {        int n = board.length;        for(int i = 0; i < n; i++){            for(int j = 0; j < n; j++){                if(board[i][j] == '.'){                    continue;                }                for(int k = 0; k < n; k++){                if (k == j) {continue;}                    if(board[i][k] == board[i][j]){//                    System.out.println("1 "+i+" "+j );                        return false;                    }                }                for(int k = 0; k < n; k++){                if (k == i) {continue;}                    if(board[k][j] == board[i][j]){//                    System.out.println("2 "+i+" "+j );                        return false;                    }                }                int rowStart = i / 3 * 3;                int rowEnd = rowStart+3;                int colStart = j / 3 * 3;                int colEnd = colStart+3;                for(int k = rowStart; k < rowEnd; k++){                    for(int l = colStart; l < colEnd; l++){                        if(k == i && l == j){                            continue;                        }                        if(board[k][l] == board[i][j]){//                        System.out.println("3 "+i+" "+j );                            return false;                        }                    }                }            }        }        return true;    }}
Python AC

class Solution:    # @param board, a 9x9 2D array    # @return a boolean    def isValidSudoku(self, board):        n = len(board)        for i in xrange(n):            for j in xrange(n):                if board[i][j] == '.':                    continue                for k in range(n):                    if k != i and board[k][j] == board[i][j]:                        return False                    if k != j and board[i][k] == board[i][j]:                        return False                rowStart = i / 3 * 3;                rowEnd = rowStart + 3                colStart = j / 3 * 3                colEnd = colStart + 3                for k in xrange(rowStart, rowEnd, 1):                    for l in xrange(colStart, colEnd, 1):                        if k == i and l == j:                            continue                        if board[k][l] == board[i][j]:                            return False        return True




0 0
原创粉丝点击