How to fill a 3x3 grid to be a valid Sudoku grid in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // shuffle
#include <random>

// To fill a 3x3 grid to be a valid Sudoku grid, you must ensure that each row, 
// column, and the 3x3 grid contains the numbers 1 through 9 without repetition.

void fillSudokuGrid(std::vector<std::vector<int>>& grid) {
    // Create a vector with numbers 1 to 9
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Shuffle the numbers randomly
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(numbers.begin(), numbers.end(), g);

    // Fill the 3x3 grid row by row
    int index = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            grid[i][j] = numbers[index++];
        }
    }
}

void printGrid(const std::vector<std::vector<int>>& grid) {
    for (const auto& row : grid) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    // Initialize an empty 3x3 grid
    std::vector<std::vector<int>> grid(3, std::vector<int>(3, 0));

    // Fill the grid with a valid Sudoku configuration
    fillSudokuGrid(grid);

    // Print the grid
    std::cout << "Generated 3x3 Sudoku Grid:\n";
    printGrid(grid);
}



/*
run:

Generated 3x3 Sudoku Grid:
5 3 6 
4 9 7 
1 2 8 

*/

 



answered Jun 1, 2025 by avibootz

Related questions

1 answer 120 views
1 answer 114 views
1 answer 182 views
1 answer 147 views
1 answer 166 views
1 answer 184 views
...