36. Valid Sudoku
package LeetCode_36 /** * 36. Valid Sudoku * https://leetcode.com/problems/valid-sudoku/description/ * * Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: 1.Each row must contain the digits 1-9 without repetition. 2.Each column must contain the digits 1-9 without repetition. 3.Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: ==A Sudoku board (partially filled) could be valid but is not necessarily solvable. ==Only the filled cells need to be validated according to the mentioned rules. ==The given board contain only digits 1-9 and the character '.'. ==The given board size is always 9x9. * */ class Solution { /* * solution: HashSet * */ fun isValidSudoku(board: Array<CharArray>): Boolean { /* * for example: * [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] * */ val set = HashSet<Char>() val size = board.size val n = board[0].size for (i in 0 until size) { set.clear() //check the rows like: //["5","3",".",".","7",".",".",".","."], for (j in 0 until n) { val char = board[i][j] if (char != '.' && set.contains(char)) { return false } set.add(char) } set.clear() //check the cols like: //["5","6",".","8","4","7",".",".","."], for (j in 0 until n) { val char = board[j][i] if (char != '.' && set.contains(char)) { return false } set.add(char) } set.clear() //check each 3x3 sub-boxes /*like: * ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ==> ["5","3",".","6",".",".",".","9","8"], * */ val x = i / 3 * 3 val y = i % 3 * 3 for (j in 0 until n) { val char = board[x + j / 3][y + j % 3] if (char != '.' && set.contains(char)) { return false } set.add(char) } } return true } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)