题意:
解题思路:
思路:1. 先遍历行,再遍历列,最后遍历3*3方块;2. 使用字典存储,遍历到对应的行列再判断字典是否包含该数字;3. 方块的判断: $x = 3 * floor($i / 3) + floor($j / 3); $y = 3 * floor($i % 3) + floor($j % 3); 比如:i = 3, j = 4 => [3,4]=>[4,1] => 表示i,j=[3,4]位于第4个box的第一个小格子
PHP代码实现:
class Solution { function isValidSudoku($board) { $row = count($board); $col = count($board[0]); for ($i = 0; $i < $row; $i++) { $rows = []; $cols = []; $cube = []; for ($j = 0; $j < $col; $j++) { if ($board[$i][$j] != '.' && in_array($board[$i][$j], $rows)) { return false; } else { array_push($rows, $board[$i][$j]); } if ($board[$j][$i] != '.' && in_array($board[$j][$i], $cols)) { return false; } else { array_push($cols, $board[$j][$i]); } $x = 3 * floor($i / 3) + floor($j / 3); $y = 3 * floor($i % 3) + floor($j % 3); if ($board[$x][$y] != '.' && in_array($board[$x][$y], $cube)) { return false; } else { array_push($cube, $board[$x][$y]); } } } return true; }}
GO代码实现:
func isValidSudoku(board [][]byte) bool { for i := 0; i < 9; i++ { rows := map[byte]bool{} cols := map[byte]bool{} cube := map[byte]bool{} for j := 0; j < 9; j++ { if board[i][j] != '.' && rows[board[i][j]] { return false } else { rows[board[i][j]] = true } if board[j][i] != '.' && cols[board[j][i]] { return false; } else { cols[board[j][i]] = true } x := 3 * (i / 3) + j / 3 y := 3 * (i % 3) + j % 3 if board[x][y] != '.' && cube[board[x][y]] { return false; } else { cube[board[x][y]] = true } } } return true}