Untitled

mail@pastecode.io avatar
unknown
java
a month ago
2.6 kB
14
Indexable
Never
public class SubSudokuValidator {

    public static void main(String[] args) {
        int[][] grid1 = {{1, 2, 3}, {3, 1, 2}, {2, 3, 1}};
        int[][] grid2 = {{1, 2, 3}, {3, 2, 1}, {3, 1, 2}};
        int[][] grid3 = {{1, 2, 3}, {3, 1, 2}, {2, 3, 1, 4}};
        int[][] grid4 = {{1}};
        int[][] grid5 = {{1, 2}, {2, 1}};
        int[][] grid6 = {{1, 3, 3}, {3, 1, 2}, {2, 3, 1}};
        int[][] grid7 = {{1, 2, 3, 4}, {4, 3, 2, 1}, {1, 3, 2, 4}, {4, 2, 3, 1}};
        int[][] grid8 = {{1, 3}, {3, 1}, {1, 3}, {3, 1}};
        int[][] grid9 = {{1, 2}, {2, 1}, {1, 2}, {2, 1}};
        int[][] grid10 = {{1, 1, 1}, {1, 6, 1}, {6, 1, 1}};
        int[][] grid11 = {{1, 2, 3, 4}, {2, 3, 1, 4}, {3, 1, 2, 4}, {4, 2, 3, 1}};
        int[][] grid12 = {{1, -2, 1}, {-2, 1, -2}, {1, -1, 2}};

        System.out.println(isValidSubSudoku(grid1));   // True
        System.out.println(isValidSubSudoku(grid2));   // False
        System.out.println(isValidSubSudoku(grid3));   // False
        System.out.println(isValidSubSudoku(grid4));   // True
        System.out.println(isValidSubSudoku(grid5));   // False
        System.out.println(isValidSubSudoku(grid6));   // False
        System.out.println(isValidSubSudoku(grid7));   // False
        System.out.println(isValidSubSudoku(grid8));   // False
        System.out.println(isValidSubSudoku(grid9));   // False
        System.out.println(isValidSubSudoku(grid10));  // False
        System.out.println(isValidSubSudoku(grid11));  // False
        System.out.println(isValidSubSudoku(grid12));  // False
    }

    public static boolean isValidSubSudoku(int[][] grid) {
        int n = grid.length;

        // Check each row and column
        for (int i = 0; i < n; i++) {
            if (!isValidArray(grid[i]) || !isValidColumn(grid, i)) {
                return false;
            }
        }

        return true;
    }

    private static boolean isValidArray(int[] arr) {
        int n = arr.length;
        boolean[] seen = new boolean[n + 1];

        for (int num : arr) {
            if (num < 1 || num > n || seen[num]) {
                return false;
            }
            seen[num] = true;
        }

        return true;
    }

    private static boolean isValidColumn(int[][] grid, int col) {
        int n = grid.length;
        boolean[] seen = new boolean[n + 1];

        for (int i = 0; i < n; i++) {
            int num = grid[i][col];
            if (num < 1 || num > n || seen[num]) {
                return false;
            }
            seen[num] = true;
        }

        return true;
    }
}
Leave a Comment