Bug in test cases for Word Search?


  • 0
    L

    Here is my code, it gave me error answer. The test case I did not go through is ["ab","cd"], "abcd". It expects false. Should it expect true? And I did output true.

        public boolean exist(char[][] board, String word) {
            if (word == null || word.length() == 0) return false;
            if (board.length * board[0].length < word.length()) return false;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (findPath(board, i, j, word)) {
                        return true;
                    }
                }
            }
            return false;
        }
        
        private boolean findPath(char[][] board, int i, int j, String word) {
            if (word.length() == 0) return false;
            if (i >= board.length || j >= board[0].length || i < 0 || j < 0) return false;
            
            if (board[i][j] == word.charAt(0)) {
                return true;
            }
            
            return findPath(board, i - 1, j, word.substring(1)) || 
                    findPath(board, i + 1, j, word.substring(1)) || 
                    findPath(board, i, j - 1, word.substring(1)) ||
                    findPath(board, i, j + 1, word.substring(1));
        }

  • 0

    false is correct. You can't jump from the 'b' cell to the 'c' cell. They're not adjacent.


  • 0
    L

    Thanks, I am tired. Right? lol


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.