LeetCode-79. Word Search

本文介绍了一种使用深度优先搜索(DFS)策略解决二维网格中查找指定单词的问题。通过递归方式遍历网格,检查单词是否能按相邻字符顺序匹配。文章提供了详细的算法解释及Java实现代码。

摘要生成于 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.

For example,
Given board =

[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.

题目要求

在给定一个数组中查找是否存在给定的字符串,查找的方式是当找到一个符合要求的字母后只能在这个字符的上下左右接着查找,并且之前已经用过的字母不能再被使用。

分析

  1. 采用图的深度优先搜索策略,对于每个相等的字母,分别去找它的上下左右的位置,如果超出搜索范围或者不相等或者已经使用过的就不算找到,当成功搜索到字符串的最后一个字母后返回true,否则返回false。
  2. 对给定的数组的每个位置都采用上述策略来搜索,只要找到了就返回true,当所有的都搜索完后仍没有找到,返回false。

相关阅读

有关图的深度优先搜索,可以参考下面几篇博客。

https://www.cnblogs.com/llhthinker/p/4844735.html
http://blog.youkuaiyun.com/jrdgogo/article/details/50834627
https://www.cnblogs.com/George1994/p/6399889.html

Java实现

class Solution {
    static boolean[][] visited;
    public boolean exist(char[][] board, String word) {
        visited=new boolean[board.length][board[0].length];
        for(int i=0;i<board.length;++i)
            for(int j=0;j<board[0].length;++j)
            {
                if(search(board,word,i,j,0))
                    return true;
            }
        return false;
    }

    public boolean search(char[][] board, String word,int i,int j,int index)
    {
        if(index==word.length())
            return true;
        if(i<0||i>=board.length||j<0||j>=board[0].length||word.charAt(index)!=board[i][j]||visited[i][j]==true)
            return false;
        visited[i][j]=true;
        if(search(board,word,i-1,j,index+1)
           ||search(board,word,i+1,j,index+1)
           ||search(board,word,i,j-1,index+1)
           ||search(board,word,i,j+1,index+1))
            return true;
        visited[i][j]=false;
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值