Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

79. 单词搜索 #34

Open
webVueBlog opened this issue Sep 4, 2022 · 0 comments
Open

79. 单词搜索 #34

webVueBlog opened this issue Sep 4, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

79. 单词搜索

Description

Difficulty: 中等

Related Topics: 数组, 回溯, 矩阵

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false

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

示例 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

示例 2:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true

示例 3:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false

提示:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • boardword 仅由大小写英文字母组成

**进阶:**你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?

Solution

Language: JavaScript

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
// 记录该元素已使用
// 上下左右不能超边界
// 如果没找到最终值的时候恢复上一个节点的值
var exist = function(board, word) {
    // 越界处理
    board[-1] = [] // 这里处理比较巧妙,利用了js的特性
    board.push([])
    // 寻找首个字母
    for (let y = 0; y < board.length; y++) {
        for (let x = 0; x < board[0].length; x++) {
            if (word[0] === board[y][x] && dfs(word, board, y, x, 0)) return true
        }
    }
    return false
}

const dfs = function(word, board, y, x, i) {
    if (i + 1 === word.length) return true
    var tmp = board[y][x]
    // 标记该元素已使用
    board[y][x] = false
    if (board[y][x+1] === word[i+1] && dfs(word, board, y, x+1, i+1)) return true
    if (board[y][x-1] === word[i+1] && dfs(word, board, y, x-1, i+1)) return true
    if (board[y+1][x] === word[i+1] && dfs(word, board, y+1, x, i+1)) return true
    if (board[y-1][x] === word[i+1] && dfs(word, board, y-1, x, i+1)) return true
    // 回溯
    board[y][x] = tmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant