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

1 Answer

0 votes
// 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.

function isValidSudoku3x3Grid($grid) {
    if (count($grid) != 3 || count($grid[0]) != 3) {
        return false; // Ensure it's a 3x3 grid
    }

    $seen = [];
    foreach ($grid as $row) {
        foreach ($row as $num) {
            if ($num < 1 || $num > 9 || in_array($num, $seen)) {
                return false; // Invalid if number is out of range or repeated
            }
            $seen[] = $num;
        }
    }

    return true; // Valid if all numbers 1-9 appear exactly once
}

$grid = [
    [5, 3, 4],
    [6, 7, 2],
    [1, 9, 8]
];

if (isValidSudoku3x3Grid($grid)) {
    echo "The grid is a valid Sudoku grid!\n";
} else {
    echo "The grid is NOT a valid Sudoku grid!\n";
}


  
/*
run:
  
The grid is a valid Sudoku grid!
 
*/

 



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

Related questions

1 answer 178 views
1 answer 185 views
1 answer 169 views
1 answer 145 views
1 answer 185 views
...