LeetCode OJ:Word Search

本文介绍了一种使用深度优先搜索算法在二维矩阵中查找单词的方法。通过遍历相邻单元格并检查字母匹配,实现高效查找。示例包括在给定矩阵中查找指定单词,以及对不同矩阵和单词的适用性进行验证。

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

Word Search

 

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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

算法思想:

深度优先搜索

struct node{
    int x,y;
    node(int a,int b):x(a),y(b){}
};
int fang[4][2]={-1,0,0,-1,1,0,0,1};
class Solution {
    int r,c;
public:
    bool dfs(int x,int y,int d,vector<vector<char> > &board,string &word,vector<vector<bool>> &visit){
        if(d==word.size()-1)return true;
        for(int i=0;i<4;i++){
            int nx=x+fang[i][0];
            int ny=y+fang[i][1];
            if(nx>=0&&nx<r&&ny>=0&&ny<c&&!visit[nx][ny]&&board[nx][ny]==word[d+1]){
                visit[nx][ny]=true;
                if(dfs(nx,ny,d+1,board,word,visit))return true;
                visit[nx][ny]=false;
            }
        }
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) {
        if(board.empty())return false;
        queue<node> que;
        r=board.size();
        c=board[0].size();
        vector<vector<bool>> visit(r);
        
        for(int i=0;i<r;i++)for(int j=0;j<c;j++)if(board[i][j]==word[0])que.push(node(i,j));
        
        while(!que.empty()){
            for(int i=0;i<r;i++)visit[i].assign(c,false);
            node cur=que.front();
            visit[cur.x][cur.y]=true;
            if(dfs(cur.x,cur.y,0,board,word,visit))return true;
            que.pop();
        }
        return false;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值