尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

元宝 专家 LeetCode 36. 有效的数独 Rust实现

元宝 专家    LeetCode 36. 有效的数独 Rust实现 LeetCode 36. 有效的数独 — Rust 实现思路利用三个二维数组分别记录行中每个数字是否已出现列中每个数字是否已出现3×3 宫中每个数字是否已出现遍历一次棋盘对每个已填充的数字进行三重检查即可。代码impl Solution {pub fn is_valid_sudoku(board: VecVec) - bool {// rows[i][d] 表示第 i 行数字 d 是否已出现let mut rows [[false; 9]; 9];let mut cols [[false; 9]; 9];let mut boxes [[false; 9]; 9];for i in 0..9 { for j in 0..9 { let c board[i][j]; if c . { continue; } let digit (c as u8 - b1) as usize; // 0~8 let box_idx (i / 3) * 3 (j / 3); // 0~8 if rows[i][digit] || cols[j][digit] || boxes[box_idx][digit] { return false; } rows[i][digit] true; cols[j][digit] true; boxes[box_idx][digit] true; } } true }}关键点要点 说明数字映射“‘1’~‘9’” →“0~8”方便做数组下标宫的编号“(i / 3) * 3 (j / 3)”将 9 个宫线性编号时间复杂度 O(1)固定 81 格空间复杂度 O(1)固定 3×9×9补充说明LeetCode 上结构体签名通常已给定为“struct Solution;”只需实现“impl Solution” 即可。题目只需验证已填充的格子空白“.” 跳过不做处理。如果棋盘本身是“[Vec]” 或“VecVec” 引用形式可根据实际签名微调参数类型。
返回列表