leetcode 79. Word Search(单词搜索)

博客围绕判断二维数组中是否存在指定单词展开。要求字母连续且不能重复使用,采用深度优先搜索(DFS)算法。先找到单词首字母,按四个方向搜索后续字母,用visited数组记录访问情况,结束路径后重置,还强调了search函数中if语句的顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

给出一个二维数组,一个string单词,让判断单词是否在数组中存在,并且字母在数组中应该是连续的,数组中的char不能重复使用

思路:

以首字母为出发点找一条完整的路径,是深度优先搜索,第一时间想到DFS。
DFS需要哪些信息呢,
board是必须的;然后结束条件是什么呢,位置(r,c)出界,当前位置已经访问过,和当前字母不一致,怎么判断整个单词已经遍历完了?用word的下标index.
当前字母是哪个,取word在index处的字母。

所以DFS需要board, (r,c), word, index的信息。

先找到单词的首字母,找到以后按4个方向搜索下一个字母,
字母不能重复使用,也就是说每个位置只能访问一次,可以用visited数组记录字母是否已经被访问,同时,这条路径结束以后,要把visited重新置为false, 不然下条路径不能从这里过了。

注意search函数中的几个if的顺序,首先要判断(r,c)是否出界,其次判断是否已经被访问过,如果已经被访问过,后面的都不需要再进行。

class Solution {
    int m = 0;
    int n = 0;
    boolean[][] visited;
    
    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;
        visited = new boolean[m][n];
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] == word.charAt(0)) {
                    if(dfs(board, i, j, word, 0)) return true;
                } 
            }
        }
        return false;
    }
    
    boolean dfs(char[][] board, int r, int c, String word, int index) {
        if(r < 0 || r >= m || c < 0 || c >= n) return false;
        if(visited[r][c]) return false;
        if(board[r][c] != word.charAt(index)) return false;
        if(index == word.length()-1) return true;
        
        visited[r][c] = true;
        if(dfs(board, r-1, c, word, index+1) || dfs(board, r, c+1, word, index+1) ||
          dfs(board, r+1, c, word, index+1) || dfs(board, r, c-1, word, index+1)) return true;   
        visited[r][c] = false;
        return false;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值