[Leetcode] Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

 

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

没啥算法,纯模拟!

 1 class Solution {

 2 public:

 3     bool isValidCell(vector<vector<char> > &board, int a, int b) {

 4         vector<bool> flag(9, false);

 5         int idx;

 6         for (int i = 0; i < 3; ++i) {

 7             for (int j = 0; j < 3; ++j) {

 8                 idx = board[a + i][b + j] - '0';

 9                 if (idx > 0 && idx <= 9 && !flag[idx])  

10                     flag[idx] = true;

11                 else if (idx > 0 && idx <= 9 && flag[idx])

12                     return false;

13             }

14         }

15         return true;

16     }

17     

18     bool isValidRow(vector<vector<char> > &board, int a) {

19         vector<bool> flag(9, false);

20         int idx;

21         for (int j = 0; j < 9; ++j) {

22             idx = board[a][j] - '0';

23             if (idx > 0 && idx <= 9 && !flag[idx])  

24                 flag[idx] = true;

25             else if (idx > 0 && idx <= 9 && flag[idx])

26                 return false;

27         }

28         return true;

29     }

30     

31      bool isValidCol(vector<vector<char> > &board, int b) {

32         vector<bool> flag(9, false);

33         int idx;

34         for (int i = 0; i < 9; ++i) {

35             idx = board[i][b] - '0';

36             if (idx > 0 && idx <= 9 && !flag[idx])  

37                 flag[idx] = true;

38             else if (idx > 0 && idx <= 9 && flag[idx])

39                 return false;

40         }

41         return true;

42     }

43     

44     bool isValidSudoku(vector<vector<char> > &board) {

45         for (int i = 0; i < 3; ++i) {

46             for (int j = 0; j < 3; ++j) {

47                 if (!isValidCell(board, 3 * i, 3 * j)) 

48                     return false;

49             }

50         }

51         for (int i = 0; i < 9; ++i) {

52             if (!isValidRow(board, i))

53                 return false;

54         }

55         for (int j = 0; j < 9; ++j) {

56             if (!isValidCol(board, j))

57                 return false;

58         }

59         return true;

60     }

61 };

 

你可能感兴趣的:(LeetCode)