36.Valid Sudoku
给定一个9*9的二维数组,求里面的数字要求横排9个、竖排9个,3*3的各自组成的9个,都组成不重复的数字。
Input:
[
["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"]
]
Output: true
思路:
将横排9个、竖排9个组成一个数组,判断这9个里面是否有重复的。难点在于3*3的方格,不好取数字,所以,一次大循环,直接取3个数组的,然后一起判断即可。由于要频繁判断9个数字是否重复,所以写一个单独的函数来判断。
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { for (int i = 0; i < 9; i++) { vector<char> vec_row, vec_column; for (int j = 0; j < 9; j++) { vec_row.push_back(board[i][j]);//横排9个字符 vec_column.push_back(board[j][i]);//竖排9个字符 } if (! (numberIsValid(vec_row) && numberIsValid(vec_column))) return false;//先判断这两个 } for (int k = 0; k < 3; k++) { int row = k * 3; vector<char> vec_sub_boxes1, vec_sub_boxes2, vec_sub_boxes3;//每一次取3个容器 for (int i = 0; i < 3; i++) { for (int x = 0; x < 3; x++) { //3*3=9次循环 vec_sub_boxes1.push_back(board[row][x]); vec_sub_boxes2.push_back(board[row][3 + x]); vec_sub_boxes3.push_back(board[row][6 + x]); //3*3*3 = 27,3个容器一次取27个字符 } row++; } if (!(numberIsValid(vec_sub_boxes1) && numberIsValid(vec_sub_boxes2) && numberIsValid(vec_sub_boxes3))) return false; } return true; } bool numberIsValid(vector<char>& nums) { int a[] = { 0,0,0,0,0,0,0,0,0,0 };//数组大小为10 int c = 0; for (auto n: nums) { if (n == '.') continue; else if (a[n - '0'] > 0) return false; else a[n - '0'] = 1; } return true; } };
总结:
由于9*9的二维数组,且数字都是 1-9的,所以在用 nums[i] - '0' 用了大小为9的数组,一直报错,原因在于,‘9’ - ‘0’ = 9 ,而数组大小为9,最大下标为8,所以一直报错。所以数组大小为10,或者用 nums[i] - '1' 。