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

1 Answer

0 votes
import java.util.HashSet;
import java.util.Set;

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

public class SudokuValidator {
    public static boolean isValidSudoku3x3Grid(int[][] grid) {
        if (grid.length != 3 || grid[0].length != 3) {
            return false; // Ensure it's a 3x3 grid
        }

        Set<Integer> seen = new HashSet<>();
        for (int[] row : grid) {
            for (int num : row) {
                if (num < 1 || num > 9 || seen.contains(num)) {
                    return false; // Invalid if number is out of range or repeated
                }
                seen.add(num);
            }
        }

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

    public static void main(String[] args) {
        int[][] grid = {
            {5, 3, 4},
            {6, 7, 2},
            {1, 9, 8}
        };

        if (isValidSudoku3x3Grid(grid)) {
            System.out.println("The grid is a valid Sudoku grid!");
        } else {
            System.out.println("The grid is NOT a valid Sudoku grid!");
        }
    }
}


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

 



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

Related questions

1 answer 112 views
1 answer 160 views
1 answer 148 views
1 answer 121 views
1 answer 158 views
...