前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >79. 单词搜索

79. 单词搜索

作者头像
ppxai
发布2023-11-18 08:36:40
1130
发布2023-11-18 08:36:40
举报
文章被收录于专栏:皮皮星球皮皮星球

79. 单词搜索

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:

代码语言:javascript
复制
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

代码语言:javascript
复制
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

代码语言:javascript
复制
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

思路:

题目意思是给一个二维数组,给一个字符串,判断字符串是否在二维数组里面,标准的dfs题目,跟走迷宫的题目一样。对于二维数组的每一位,往上下左右四个放下探索,走过的路径用一个特殊字符标记一下就行,每找到单词中的一个字母,就结果加一,最终如果探索结果和单词长度相同,单词肯定就在二维数组里面。

代码:

golang:

代码语言:javascript
复制
func exist(board [][]byte, word string) bool {
    var maxLen = 0
    var words = []byte(word)
    var maxMatch = math.MinInt32
    for i := 0; i < len(board); i++ {
        for j := 0; j < len(board[0]); j++ {
            maxMatch = max(maxMatch, bfs(board, words, i, j, 0, maxLen))
            if maxMatch == len(word) {
                return true
            }
        }
    }
    return maxMatch == len(word)
}

var dests = [][]int{
    []int{-1, 0}, 
    []int{1, 0}, 
    []int{0, -1}, 
    []int{0, 1},
}

func bfs(board [][]byte, words []byte, i, j, idx int, maxLen int) int {
    if i < 0 || j < 0 || i >= len(board) || j >= len(board[0]) {
        return maxLen
    }

    if idx == len(words) {
        return maxLen
    }

    if board[i][j] != words[idx] {
        return maxLen
    }

    maxLen++

    // 四个方向继续探索
    maxMatch := maxLen
    var nowMaxLen = 0
    for _, dest := range dests {

        nowVal := board[i][j]
        board[i][j] = '-'

        nowMaxLen = maxLen
        idx++
        maxMatch = max(maxMatch, bfs(board, words, i+dest[0], j+dest[1], idx, maxLen))
        idx--
        maxLen = nowMaxLen
        board[i][j] = nowVal
    }

    return maxMatch
}

func max(i, j int) int {
    if i > j {
        return i
    } 
    return j
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-07-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 79. 单词搜索
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档