LeetCode题解:Word Search

本文介绍了一个二维网格中查找指定单词的算法实现。通过深度优先搜索(DFS)的方式遍历网格,寻找与目标单词匹配的路径。文章提供了详细的C++代码示例,并解释了如何避免重复使用同一格子。

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.

思路:

题目没什么特别的难度,就是做一个深搜即可。

题解:

class Solution {
public:
    typedef vector<vector<char>> board_t;
    
    int N, M;
    board_t used_mark;
    
    bool navigate(const board_t& board, const string& word,
                  int board_i, int board_j, int word_offset)
    {
        if (board_i < 0 || board_j < 0 ||
                board_i >= N || board_j >= M ||
                used_mark[board_i][board_j] != 0 ||
                board[board_i][board_j] != word[word_offset])
            return false;
    
        if (word_offset == word.size() - 1)
            return true;
    
        used_mark[board_i][board_j] = 1;
    
        if ( navigate(board, word, board_i, board_j - 1, word_offset + 1) ||
                navigate(board, word, board_i, board_j + 1, word_offset + 1) ||
                navigate(board, word, board_i - 1, board_j , word_offset + 1) ||
                navigate(board, word, board_i + 1, board_j , word_offset + 1) )
            return true;
    
        used_mark[board_i][board_j] = 0;
        return false;
    }
    
    bool exist(const board_t& board, const string& word)
    {
        N = board.size();
        M = board[0].size();
    
        used_mark.resize(N);
        for (auto & m : used_mark)
        {
            m.resize(M);
            fill(begin(m), end(m), 0);
        }
    
        for (auto i = 0; i < N; ++i)
            for (auto j = 0; j < M; ++j)
                if (board[i][j] == word[0])
                    if (navigate(board, word, i, j, 0))
                        return true;
    
        return false;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值