LeetCode刷题实战36: 有效的数独
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 有效的数独,我们先来看题面:
https://leetcode-cn.com/problems/valid-sudoku/
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
题意
样例
题解
class Solution {
public boolean isValidSudoku(char[][] board) {
//最外层循环,每次循环并非只是处理第i行,而是处理第i行、第i列以及第i个3x3的九宫格
for(int i = 0; i < 9; i++){
HashSet<Character> line = new HashSet<>();
HashSet<Character> col = new HashSet<>();
HashSet<Character> cube = new HashSet<>();
for(int j = 0; j < 9; j++){
if('.' != board[i][j] && !line.add(board[i][j]))
return false;
if('.' != board[j][i] && !col.add(board[j][i]))
return false;
int m = i/3*3+j/3;
int n = i%3*3+j%3;
if('.' != board[m][n] && !cube.add(board[m][n]))
return false;
}
}
return true;
}
}
上期推文: