leetcode 36 c++

C++ Solution for LeetCode Problem 36: Valid Sudoku

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        vector<unordered_set<int>> rows(9), cols(9), boxes(9);

        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                char num = board[i][j];
                if (num != '.') {
                    int n = num - '0';
                    int box_index = (i / 3) * 3 + j / 3;
                    if (rows[i].count(n) || cols[j].count(n) || boxes[box_index].count(n)) {
                        return false;
                    }
                    rows[i].insert(n);
                    cols[j].insert(n);
                    boxes[box_index].insert(n);
                }
            }
        }
        return true;
    }
};

Explanation:

  1. Create three vectors of unordered sets to keep track of the numbers in each row, column, and box.
  2. Loop through each cell of the Sudoku board.
  3. For each cell, check if the number is a digit (not a dot).
  4. Calculate the index of the box the cell belongs to.
  5. Check if the number already exists in the current row, column, or box. If it does, return false.
  6. If the number doesn't exist in any of the sets, insert it into the sets.
  7. If the loop completes without finding any conflicts, return true.