【1】【leetcode-79】 单词搜索

(典型dfs,知道思想写错)

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.

public class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(dfs(board, word, visited, i, j, m, n, 0))
                   return true;
            }
        }
        return false;
    }
     
    private boolean dfs(char[][] board, String word, boolean[][] visited, int i, int j, int m, int n, int count){
        if(count == word.length()){
            return true;
        }
        if(i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word.charAt(count))
            return false;
        if(visited[i][j])
            return false;
        visited[i][j] = true;
        boolean res = dfs(board, word, visited, i - 1, j, m, n, count + 1) || 
            dfs(board, word, visited, i + 1, j, m, n, count + 1) || 
            dfs(board, word, visited, i, j - 1, m, n, count + 1)||
            dfs(board, word, visited, i, j + 1, m, n, count + 1);
        visited[i][j] = false;
        return res;
    }
}
 参考2:
class Solution {
    public boolean exist(char[][] board, String word) {
        // 标志位,初始为false
        int row = board.length, col = board[0].length;
        boolean[][] flag = new boolean[row][col];
        for(int r = 0; r < row; r++){
            for(int c = 0; c < col; c++){
                if(isSolution(board,r,c,flag,word,0))
                    return true;
            }
        }
        return false;
    }
    public boolean isSolution(char[][] board,int r, int c, boolean[][] flag, String word, int start){
        // 递归出口
        if(r<0||r>=board.length||c<0||c>=board[0].length||board[r][c]!=word.charAt(start)||flag[r][c]==true)
            return false;
        // 匹配成功
        if(start==word.length()-1)
            return true;
        // 标记已走过的位置
        flag[r][c] = true; 
        // 上下左右递归查找
        if(isSolution(board,r-1,c,flag,word,start+1)
        ||isSolution(board,r+1,c,flag,word,start+1)
        ||isSolution(board,r,c-1,flag,word,start+1)
        ||isSolution(board,r,c+1,flag,word,start+1)){
            return true;
        }
        // 没匹配到则把标记为改回去!!!
        flag[r][c] = false;
        return false;
    }
}
原文地址:https://www.cnblogs.com/twoheads/p/10638057.html