判断数独(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'.'.

A partially filled sudoku which is valid.

代码:
方式1:
链接:https://www.nowcoder.com/questionTerminal/8240bcdab4eb496fb6c4ba634fc67921
来源:牛客网

import java.util.HashSet;
import java.util.Set;
 
/**
 * 36. Valid Sudoku
 *
 * @author Jacob
 *
 */
public class Demo1 {
    /*
     * 题意:让你判断这是否是一个正确的数独,
     * 即确定每一行,每一列以及每一个九宫格是否有相同的数字
     * HashSet的add方法,当添加成功(即set中不含有该元素)返回true
     */
    public boolean isValidSudoku(char[][] board) {
        // 每一个大循环确定一行,一列,一个九宫格
        for (int i = 0; i < 9; i++) {
            Set<Character> row = new HashSet<Character>();
            Set<Character> col = new HashSet<Character>();
            Set<Character> cube = new HashSet<Character>();
 
            for (int j = 0; j < 9; j++) {
                // 第i行
                if (board[i][j] != '.' && !row.add(board[i][j]))
                    return false;
                // 第i列
                if (board[j][i] != '.' && !col.add(board[j][i]))
                    return false;
                //
                int cubeRow = 3 * (i / 3) + j / 3, cubeCol = 3 * (i % 3) + j % 3;
                if (board[cubeRow][cubeCol] != '.' && !cube.add(board[cubeRow][cubeCol]))
                    return false;
            }
        }
        return true;
    }
}

方式2:
public class Solution {
    public boolean isValidSudoku(char[][] board) {
      for(int i=0;i<9;i++){
            int[]flag=new int[10];
            for(int j=0;j<9;j++){
                if(board[i][j]!='.'){
                    if(flag[board[i][j]-'0']==0)
                        flag[board[i][j]-'0']++;
                    else{
                        return false;
                    }
                }
            }
        }
        for(int i=0;i<9;i++){
            int[]flag=new int[10];
            for(int j=0;j<9;j++){
                if(board[j][i]!='.'){
                    if( flag[ board[j][i]-'0' ] ==0)
                        flag[board[j][i]-'0']++;
                    else{
                        return false;
                    }
                }
            }
        }
        for(int i=0 ;i <9;i++){
            int[]flag=new int[10];
            for(int j=0;j<9;j++){
                int left=(i%3)*3+j%3;
                int top=((int)i/3)*3+j/3;
                if(board[left][top]!='.'){
                    if( flag[ board[left][top]-'0' ]==0){
                        flag[ board[left][top]-'0' ]++;
                    }
                    else{
                        return false;
                    }
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34360094/article/details/82589668
今日推荐