Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,652 questions

51,529 answers

573 users

How to check if a 3x3 grid is a valid Sudoku grid in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

// Sudoku solution must satisfy all of the following rules:
// Each of the digits 1-9 must occur once in each row.
// Each of the digits 1-9 must occur once in each column.
// Each of the digits 1-9 must occur once in each 3x3 grid.

#define SIZE 3

bool isValidSudoku3x3Grid(int grid[SIZE][SIZE]) {
    int seen[10] = {0}; // Array to track numbers 1-9

    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            int num = grid[i][j];

            if (num < 1 || num > 9 || seen[num]) {
                return false; // Invalid if number is out of range or repeated
            }
            seen[num] = 1;
        }
    }
    
    return true; // Valid if all numbers 1-9 appear exactly once
}

void printResult(bool valid) {
    if (valid) {
        printf("The grid is a valid Sudoku grid!\n");
    } else {
        printf("The grid is NOT a valid Sudoku grid!\n");
    }
}

int main() {
    int grid[SIZE][SIZE] = {
        {5, 3, 4},
        {6, 7, 2},
        {1, 9, 8}
    };

    printResult(isValidSudoku3x3Grid(grid));
    
    return 0;
}



/*
run:

The grid is a valid Sudoku grid!

*/

 



answered May 30, 2025 by avibootz
edited May 30, 2025 by avibootz

Related questions

1 answer 57 views
1 answer 55 views
1 answer 110 views
1 answer 103 views
1 answer 74 views
...