A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
Solution:
public class Solution { // DO NOT MODIFY THE LIST. IT IS READ ONLY public int isValidSudoku(final List<String> A) { for (int i = 0; i < 9; i ++) { String row = A.get(i); for (int j = 0; j < 9; j ++) { char c = row.charAt(j); if (c != '.') { if (!validate(A, i, j)) { return 0; } } } } return 1; }
private boolean validate(List<String> A, int x, int y) { Set<Character> row = new HashSet<>(); Set<Character> col = new HashSet<>(); Set<Character> zone = new HashSet<>(); for (int i = 0; i < 9; i ++) { String r = A.get(i); for (int j = 0; j < 9; j ++) { char c = r.charAt(j); if (c == '.') continue; if (i == x) { if (!row.add(c)) { return false; } } if (j == y) { if (!col.add(c)) { return false; } } if (i / 3 == x / 3 && j / 3 == y / 3) { if (!zone.add(c)) { return false; } } } } return true; } }