将节点标记为在dfs中访问以进行单词搜索

ijxebb2r  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(213)

这是leetcode上的单词搜索问题。我在下面提供了一张图片,很好地解释了这一点。我的方法是在电路板中的每个字母上都有一个dfs(通过遍历double-for循环),我这样做是为了让我的dfs函数可以从每个字母开始,我可以得到所有不同的单词。
我通过传递一个布尔数组将节点标记为已访问,如果我看到了该节点,则该值将更改为true,如果它没有指向路径,则该值将更改回false。我想这就是我搞砸的地方。我不知道如何正确地将节点标记为在这里访问的,如果我不这样做,那么我会得到一个无限循环。
当我运行我的程序并打印出dfs正在生成的字符串时,我没有得到所有可能的字符串。这就是我想弄明白的,如何得到所有的字符串。
您也可以在leetcode中运行代码。谢谢您!

class Solution {
    public boolean exist(char[][] board, String word) {

        if(board == null || word == null) {
            return false;
        }

        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[i].length; j++) {
                List<Character> tempList = new ArrayList<>();
                tempList.add(board[i][j]);
                boolean[][] tempBoard = new boolean[board.length][board[0].length];
                if(wordExists(i, j, word, tempList, board, tempBoard)) {
                    return true;
                } 
                else{
                     tempList.remove(tempList.size() - 1);
                }
            }
        }   
        return false;
    }

    public static boolean wordExists(int sr, int sc, String word, List<Character> list, char[][] board, boolean[][] tempBoard) {
        StringBuilder sb = new StringBuilder();
        for(Character c : list) {
            sb.append(c);
        }

        System.out.println(sb.toString());

        if(word.equals(sb.toString())) {
            return true;
        }

        final int[][] SHIFTS = {
            {0,1},
            {1,0},
            {0,-1},
            {-1,0}
        };
        tempBoard[sr][sc] = true;
        for(int[] shift : SHIFTS) {
            int row = sr + shift[0];
            int col = sc + shift[1];

            if(isValid(board, row, col, tempBoard)) {
                list.add(board[row][col]);

                if(wordExists(row, col, word, list, board, tempBoard)) {
                    return true;
                }
                tempBoard[sr][sc] = false;
                list.remove(list.size() - 1);
            }
        }
        return false;
    }

    public static boolean isValid(char[][] board, int row, int col, boolean[][] tempBoard) {
        if(row >= 0 && row < board.length && col >= 0 && col < board[row].length && tempBoard[row][col] != true) {
            return true;
        }
        return false;
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题