|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class example2 { |
| 4 | +public static boolean notInRow(char arr[][], int row) |
| 5 | +{ |
| 6 | + |
| 7 | +HashSet<Character> st = new HashSet<>(); |
| 8 | + |
| 9 | +for (int i = 0; i < 9; i++) { |
| 10 | +if (st.contains(arr[row][i])) |
| 11 | +return false; |
| 12 | + |
| 13 | +if (arr[row][i] != '.') |
| 14 | +st.add(arr[row][i]); |
| 15 | +} |
| 16 | +return true; |
| 17 | +} |
| 18 | + |
| 19 | +public static boolean notInCol(char arr[][], int col) |
| 20 | +{ |
| 21 | +HashSet<Character> st = new HashSet<>(); |
| 22 | + |
| 23 | +for (int i = 0; i < 9; i++) { |
| 24 | + |
| 25 | +// If already encountered before, |
| 26 | +// return false |
| 27 | +if (st.contains(arr[i][col])) |
| 28 | +return false; |
| 29 | + |
| 30 | +// If it is not an empty cell, |
| 31 | +// insert value at the current |
| 32 | +// cell in the set |
| 33 | +if (arr[i][col] != '.') |
| 34 | +st.add(arr[i][col]); |
| 35 | +} |
| 36 | +return true; |
| 37 | +} |
| 38 | + |
| 39 | +public static boolean notInBox(char arr[][], int startRow, int startCol) |
| 40 | +{ |
| 41 | +HashSet<Character> st = new HashSet<>(); |
| 42 | + |
| 43 | +for (int row = 0; row < 3; row++) { |
| 44 | +for (int col = 0; col < 3; col++) { |
| 45 | +char curr = arr[row + startRow][col + startCol]; |
| 46 | + |
| 47 | +if (st.contains(curr)) |
| 48 | +return false; |
| 49 | + |
| 50 | +if (curr != '.') |
| 51 | +st.add(curr); |
| 52 | +} |
| 53 | +} |
| 54 | +return true; |
| 55 | +} |
| 56 | +public static boolean isValid(char arr[][], int row, |
| 57 | +int col) |
| 58 | +{ |
| 59 | +return notInRow(arr, row) && notInCol(arr, col) |
| 60 | +&& notInBox(arr, row - row % 3, col - col % 3); |
| 61 | +} |
| 62 | + |
| 63 | +public static boolean isValidConfig(char arr[][], int n) |
| 64 | +{ |
| 65 | +for (int i = 0; i < n; i++) { |
| 66 | +for (int j = 0; j < n; j++) { |
| 67 | + |
| 68 | +// If current row or current column or |
| 69 | +// current 3x3 box is not valid, return |
| 70 | +// false |
| 71 | +if (!isValid(arr, i, j)) |
| 72 | +return false; |
| 73 | +} |
| 74 | +} |
| 75 | +return true; |
| 76 | +} |
| 77 | + |
| 78 | +public static void main(String[] args) |
| 79 | +{ |
| 80 | +char[][] board = new char[][] { |
| 81 | +{ '5', '3', '.', '.', '7', '.', '.', '.', '.' }, |
| 82 | +{ '6', '.', '.', '1', '9', '5', '.', '.', '.' }, |
| 83 | +{ '.', '9', '8', '.', '.', '.', '.', '6', '.' }, |
| 84 | +{ '8', '.', '.', '.', '6', '.', '.', '.', '3' }, |
| 85 | +{ '4', '.', '.', '8', '.', '3', '.', '.', '1' }, |
| 86 | +{ '7', '.', '.', '.', '2', '.', '.', '.', '6' }, |
| 87 | +{ '.', '6', '.', '.', '.', '.', '2', '8', '.' }, |
| 88 | +{ '.', '.', '.', '4', '1', '9', '.', '.', '5' }, |
| 89 | +{ '.', '.', '.', '.', '8', '.', '.', '7', '9' } |
| 90 | +}; |
| 91 | + |
| 92 | +// Function call |
| 93 | +System.out.println( |
| 94 | +(isValidConfig(board, 9) ? "YES" : "NO")); |
| 95 | +} |
| 96 | +} |
| 97 | + |
0 commit comments