LeetCode 79. Word Search

本文介绍了一种使用回溯加深度优先搜索算法解决二维网格中查找指定单词的问题。通过递归方式遍历网格,检查单词是否能由相邻字母构成,同一字母单元格不可重复使用。

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

分析:

回溯+深度搜索,用数组存放四个方向,依次进行深搜

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int n=board.size(),m;
        if(n>0)  m=board[0].size();
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(board[i][j]==word[0]){
                    memset(vis,0,sizeof(vis));
                    vis[i][j]=1;
                    dfs(1,i,j,board,word,n,m);
                    if(flag) return flag;
                }
            }
        }
        return false;
    }
private:
    int dic[4][2]={1,0,-1,0,0,1,0,-1};
    int vis[1005][1005];
    bool flag=false;
    void dfs(int index,int r,int l,vector<vector<char>>& board, string word,int n,int m){
        if(flag) return;
        if(index==word.length()){
            flag=true;
            return;
        }
        for(int i=0;i<4;i++){
            int rr=dic[i][0]+r;
            int ll=dic[i][1]+l;
            if(rr<0||rr>=n||ll<0||ll>=m||vis[rr][ll]==1||board[rr][ll]!=word[index]) continue;
            vis[rr][ll]=1;
            dfs(index+1,rr,ll,board,word,n,m);
            vis[rr][ll]=0;
        }
    }
    
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值