LeetCode 79. Word Search

这篇文章是 LeetCode 79. Word Search.md 的分析与解法。

问题描述

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.

这道题的意思就是在给定的字母板上寻找给定的单词,规则是从一个字母开始垂直或者水平方向上开始寻找,同一个位置的字母只能在路径上经过一次。

问题分析

这个问题首先能想到的方法就是暴力搜索,从字母板的(0, 0)位置开始搜索,到(n, n)位置结束。如果在搜索的过程中找到了给定的单词就直接返回。

以下图为例,假设我们要搜索的单词是『BED』,搜索顺序为『上下左右』:

搜索过程如下:

  1. 从(0, 0)位置的 A 开始搜索,A 与给定单词的[0]位置的字母不匹配,到(1, 0)位置;
  2. (1, 0)位置的 B 与给定单词的[0]位置的字母相同,按照 B 的上下左右的方向依次搜索,已经经过的位置不再搜索;
  3. 搜索至(1,1)位置的 E,与给定单词的[1]的字母相同,按照 E 的上下左右的方向依次搜索,已经经过的位置不再搜索;
  4. 直到搜索到 D,完成 BED 的搜索,返回。

代码实现

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size() == 0 || word.length() == 0 ){
            return false;
        }
        for(int i = 0; i < board.size(); i++){
            for(int j = 0; j < board[i].size(); j++){
                if(search(board, word, i, j, 0)){
                    return true;
                }
            }
        }
        return false;
    }

    bool search(vector<vector<char>>& board, string word, int x, int y, int pos){
        if(pos == word.length()){
            return true;
        }
        if(x < 0 || y < 0 || y >= board[x].size() || x >= board.size()){
            return false;
        }
        if(board[x][y] != word[pos]){
            return false;
        }
        char temp = board[x][y];
        board[x][y] = '*';

        bool result = search(board, word, x-1, y, pos+1)
        || search(board, word, x+1, y, pos+1)
        || search(board, word, x, y+1, pos+1)
        || search(board, word, x, y-1, pos+1);

        board[x][y] = temp;

        return result;
    }
};

本文的完整代码详见我的 GitHub


本文的版权归作者 罗远航 所有,采用 Attribution-NonCommercial 3.0 License。任何人可以进行转载、分享,但不可在未经允许的情况下用于商业用途;转载请注明出处。感谢配合!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值