Leetcode 36 Valid Sudoku

    技术2025-01-10  13

    思路一: 三次循环矩阵,分别筛查3个constraints。很简单,直接上代码:

    class Solution { public boolean isValidSudoku(char[][] board) { int m = board.length; int n = board[0].length; // check rows for(int i = 0; i < m; i++){ Set<Character> set = new HashSet<>(); for(int j = 0; j < n; j++){ if(board[i][j] == '.') continue; if(!set.add(board[i][j])) return false; } } // check columns for(int i = 0; i < n; i++){ Set<Character> set = new HashSet<>(); for(int j = 0; j < m; j++){ if(board[j][i] == '.') continue; if(!set.add(board[j][i])) return false; } } // check blocks for(int i = 0; i <= 6; i = i+3){ for(int j = 0; j <= 6; j =j + 3){ if(!isValidSubBoard(board,i,j)) return false; } } return true; } private boolean isValidSubBoard(char[][] board, int row, int col) { Set<Character> set = new HashSet<>(); for(int i = row; i < row + 3; i++){ for(int j = col; j < col + 3; j++){ if(board[i][j] == '.') continue; if(!set.add(board[i][j])) return false; } } return true; } }

    思路二: discussion high votes solution。遍历一次矩阵,将每一个元素加入到set中,在加入的过程中判断是否满足三个条件。加入到set中的是string。这边我讲的很笼统,直接看代码吧,代码非常的readable。

    class Solution { public boolean isValidSudoku(char[][] board) { Set<String> set = new HashSet<>(); for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ char number = board[i][j]; if(number != '.'){ if(!set.add(number + "in row" + i) || !set.add(number + "in column" + j) || !set.add(number + "in block" + (i / 3 * 3) + (j / 3))) return false; } } } return true; } }

    总结: 无

    Processed: 0.009, SQL: 9