标签:cti rap 存在 common col alt continue nta als
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
1-9
在每一行只能出现一次。1-9
在每一列只能出现一次。1-9
在每一个以粗实线分隔的 3x3
宫内只能出现一次。下面是Rust测试用的数组,可以复制过去。
let vec: Vec<Vec<char>> = vec![ vec![‘5‘, ‘3‘, ‘.‘, ‘.‘, ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘], vec![‘6‘, ‘.‘, ‘.‘, ‘1‘, ‘9‘, ‘5‘, ‘.‘, ‘.‘, ‘.‘], vec![‘.‘, ‘9‘, ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘], vec![‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘3‘], vec![‘4‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘3‘, ‘.‘, ‘.‘, ‘1‘], vec![‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘], vec![‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘8‘, ‘.‘], vec![‘.‘, ‘.‘, ‘.‘, ‘4‘, ‘1‘, ‘9‘, ‘.‘, ‘.‘, ‘5‘], vec![‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘.‘, ‘7‘, ‘9‘], ];
题解: 这个题就是一堆数组查重,我的思路是用变量去表示每个元素,过滤掉 ‘.‘,然后放入map,判断是否存在,下面是代码 4ms;
use std::collections::HashMap; let mut j = 0; // 行 let mut k = 0; // 列 for i in 0..9 { let mut map: HashMap<char, char> = HashMap::new(); let mut map2: HashMap<char, char> = HashMap::new(); let mut map3: HashMap<char, char> = HashMap::new(); for j in 0..9 { if board[i][j] != ‘.‘ { if map.contains_key(&board[i][j]) { return false; } map.insert(board[i][j], ‘0‘); } if board[j][i] != ‘.‘ { if map2.contains_key(&board[j][i]) { return false; } map2.insert(board[j][i], ‘0‘); } } if k == 9 { k = 0; j = j + 3; } let mut x = j; let mut y = k; for _ in 0..9 { if board[x][y] != ‘.‘ { if map3.contains_key(&board[x][y]) { return false; } map3.insert(board[x][y], ‘0‘); } if y == 2 { x = x + 1; y = 0; continue; } if y == 5 { x = x + 1; y = 3; continue; } if y == 8 { x = x + 1; y = 6; continue; } y = y + 1 } k = k + 3; } return true;
大佬的解法,看着更赏心悦目 0ms,原理都差不多,只是放在了数组,这种查重时候 0..10 的数组
let mut row = [[0u8; 10]; 9]; let mut col = [[0u8; 10]; 9]; let mut my_box = [[0u8; 10]; 9]; for i in 0..9 { for j in 0..9 { if board[i][j] == ‘.‘ { continue; }; let cur_number = board[i][j].to_string().parse::<usize>().unwrap(); print!("{} ", cur_number); if row[i][cur_number] != 0 { return false; } if col[j][cur_number] != 0 { return false; } if my_box[j / 3 + (i / 3) * 3][cur_number] != 0 { return false; } row[i][cur_number] = 1; col[j][cur_number] = 1; my_box[j / 3 + (i / 3) * 3][cur_number] = 1; } } return true;
标签:cti rap 存在 common col alt continue nta als
原文地址:https://www.cnblogs.com/Addoil/p/13396035.html