【leetcode】79 Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

在这里插入图片描述
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true

DFS + 回溯,
1.选择起点,可以看出起点不止一个
2.下一个字符有可能在当前点的上下左右四个方向,判断这四个方向是否能走,判断一下该方向上的字符是否是word里的下一个字符,判断该字符是否已经访问过(使用visited数组保存每个点是否被访问)
3. 当四个方向都走不通,且此时的字符还不是目标值,代表此路不通
4. 回溯:当选点错误时,要撤销访问过这个点的痕迹,去尝试别的路线

var exist = function(board, word) {
    
    let res = false;
    let visited = [...Array(board.length)].map(() => Array(board[0].length).fill(0))
    
    const dfs = (i, j, str, index) => {
        if(str.length === word.length) {
            if(str === word) {
                res = true;
            }
            return;
        }
        if(i - 1 >= 0 && board[i - 1][j] === word[index + 1] && !visited[i - 1][j]) {
            visited[i][j] = 1
            dfs(i - 1, j, str + word[index + 1], index+1);
            visited[i][j] = 0
        }
        if(i + 1 < board.length && board[i + 1][j] === word[index + 1] && !visited[i + 1][j]) {
            visited[i][j] = 1
            dfs(i + 1, j, str + word[index + 1], index+1);
            visited[i][j] = 0
        }
        if(j - 1 >= 0 && board[i][j - 1] === word[index + 1] && !visited[i][j - 1]) {
            visited[i][j] = 1
            dfs(i, j - 1, str + word[index + 1], index+1);
            visited[i][j] = 0
        }
        if(j + 1 < board[i].length && board[i][j + 1] === word[index + 1] && !visited[i][j + 1]) {
            visited[i][j] = 1
            dfs(i, j + 1, str + word[index + 1], index+1);
            visited[i][j] = 0
        }
    }
    
    for(let i = 0; i < board.length; i++) {
        for(let j = 0; j < board[i].length; j++) {
            if(board[i][j] === word[0]) {
                dfs(i, j, word[0], 0)
            }
        }
    }  
    return res
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值