LeetCode 79. Word Search (dfs)

Word Search

Medium

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

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

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

题意

在字母矩阵中查找单词是否存在,上下左右的字母可以连成单词,字母不能重复使用

思路

典型dfs。首先顺序遍历整个矩阵查找是否能匹配单词的首字母,匹配上首字母后再进行dfs从上下左右4个方向查找单词。因为“字母不能重复使用”,所以使用过的矩阵位置要置零。记得dfs函数返回false之前将已经置零的位置改回来。

代码

func exist(board [][]byte, word string) bool {
    m := len(board)
    if word == "" {
        return true
    }
    if m == 0 {
        return false
    }
    n := len(board[0])
    L := len(word)
    for i:=0; i<m; i++ {
        for j:=0; j<n; j++ {
            if board[i][j] == word[0] && dfs(board, m, n, i, j, word, L, 0) {
                return true
            }
        }
    }
    return false
}

func dfs(board [][]byte, m int, n int, i int, j int, word string, L int, cnt int) bool {
    if cnt == L-1 {
        return true
    }
    cnt++
    tmp := board[i][j]
    board[i][j] = 0
    if i > 0 && board[i-1][j] == word[cnt] && dfs(board, m, n, i-1, j, word, L, cnt) {
        return true 
    }
    if j > 0 && board[i][j-1] == word[cnt] && dfs(board, m, n, i, j-1, word, L, cnt) {
        return true 
    }
    if i < m-1 && board[i+1][j] == word[cnt] && dfs(board, m, n, i+1, j, word, L, cnt) {
        return true 
    }
    if j < n-1 && board[i][j+1] == word[cnt] && dfs(board, m, n, i, j+1, word, L, cnt) {
        return true 
    }
    board[i][j] = tmp
    return false
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值