HT36ValidSudoku

来源:互联网 发布:人工智能三个阶段 编辑:程序博客网 时间:2024/06/05 16:30

Clue

  • Not familiar with hash tables. Didn’t understand the problem ‘VALID’.
  • Read others solutions, then understand, not duplicated exists is fine.

Logic Flaw

  • Char&Integer
    • When adding into a hashset, if we use + in the add() function, pay attention to Char with Integers. If you + them, it will return the integer. Should use String.
    • add("B"+ i/3 + j/3 + curr)will return four characters, e.g. B029
  • Don’t forget to deal with the ‘.’
  • Trick of ||, not all three will be executed

重大错误

    public static boolean isValidSudoku(char[][] board) {        Set s = new HashSet();        for (int i = 0; i < 9; i++) {            for (int j = 0; j < 9 && board[i][j] != '.'; j++) {                char curr = board[i][j];                if (!s.add("H"+ i + curr) || !s.add("V"+ j + curr)                    || !s.add("B"+ i/3 + j/3 + curr)                    ) {                    return false;                }            }        }        printSet(s);        return true;    }

与下面的代码不同

    public static boolean isValidSudoku(char[][] board) {        Set s = new HashSet();        for (int i = 0; i < 9; i++) {            for (int j = 0; j < 9; j++) {                char curr = board[i][j];                if (curr == '.') continue;                if (!s.add("H"+ i + curr) || !s.add("V"+ j + curr)                 || !s.add("B"+ i/3 + j/3 + curr)) {                    return false;                }            }        }        return true;    }

因为第二个for循环中,第二个参数多了一个限制条件,当不满足时,并不会再执行第二个for循环,而会跳到i++的下一层数组上。

0 0