-1

コードのどこが間違っているのか知りたいので、期待される出力を得るのを手伝ってください。前もって感謝します。##リートコードからの単語検索 II##:

コード:

class Solution {

    public List<String> findWords(char[][] board, String[] words) {

        List<String> result = new ArrayList<String>();

        if (board.length <= 0 || words.length <= 0) {
            return result;
        }

        for (int i = 0; i < words.length; i++) {

            if (result.contains(words[i])) {
                continue;
            }

            for (int j = 0; j < board.length; j++) {

                for (int k = 0; k < board[0].length; k++) {

                    if (result.contains(words[i])) {
                        break;
                    }

                    if (words[i].charAt(0) == board[j][k]) {

                        boolean isVisited[][] = new boolean[board.length][board[0].length];
                        for (boolean a[] : isVisited) {
                            Arrays.fill(a, false);
                        }
                        if (dfs(j, k, words[i], 0, board, isVisited)) {
                            result.add(words[i]);

                        }

                    }
                }
            }
        }

        return result;
    }

    boolean dfs(int row, int col, String word, int index, char[][] board, boolean[][] isVisited) {

        if (index == word.length()) {
            return true;
        } else if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || isVisited[row][col] || board[row][col] != word.charAt(index)) {
            return false;
        } else {
            System.out.println(word.charAt(index) + " = " + index);
            isVisited[row][col] = true;
            return dfs(row + 1, col, word, index + 1, board, isVisited)
                    || dfs(row, col + 1, word, index + 1, board, isVisited)
                    || dfs(row - 1, col, word, index + 1, board, isVisited)
                    || dfs(row, col - 1, word, index + 1, board, isVisited);

        }
    }

}

入力:

[["a","b","c"],["a","e","d"],["a","f","g"]]
["abcdefg","gfedcbaaa","eaabcdgfa","befa","dgc","ade"]

私の出力:

["abcdefg","gfedcbaaa","befa"]

期待される:

["abcdefg","befa","eaabcdgfa","gfedcbaaa"]
4

1 に答える 1