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", -> returnstrue,
word ="SEE", -> returnstrue,
word ="ABCB", -> returnsfalse. 

思路:我们首先分析问题,如何去找匹配的字符串,第一步先是从数组中找到匹配word第一个字符的位置,接下来就只能在这个位置的四个方向(上下左右)递归搜索,看是否有匹配word的字符串,如果这些位置中的字母和word下一个字母相等,则从这些位置继续搜索。我们每次从一个元素出发时,对board中的元素已访问的标志可以设一个访问标志数组,也可以把已访问的元素设置为某个特殊字符,该题中设为”#“,如果搜索失败,我们需要恢复这个字母,虽然单次搜索字符不能重复,但是每次从一个新的元素出发,这个字符还是可以使用的。

实现代码:

              class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        if(word.size() == 0) return true;  
        int row = board.size();  
        int col = board[0].size();  
        if(row == 0 || col == 0) return false;  
        for(int i = 0; i < row; i++)  
        {  
            for(int j = 0; j < col; j++)  
            {  
                if(board[i][j] == word[0] && exist_helper(board, word, i, j, 0))  //先找到首元素的位置(可能有多个);
                    return true;  
            }  
        }  
        return false;  
    }  
  
private:  
    bool exist_helper(vector<vector<char>> board, string word, int i, int j, int index)  
    {  
        //如果word的所有字符都匹配成功,index到达word.size()-1,递归结束,返回true  
        if(index == word.size()-1) return true;  
          
        char ctmp = board[i][j];  
        board[i][j] = '#';  
          
        //上  
        if(i-1 >= 0 && board[i-1][j] == word[index+1])  
            if(exist_helper(board, word, i-1, j, index+1))  
                return true;  
          
        //下  
        if(i+1 < board.size() && board[i+1][j] == word[index+1])  
            if(exist_helper(board, word, i+1, j, index+1))  
                return true;  
          
        //左  
        if(j-1 >= 0 && board[i][j-1] == word[index+1])  
            if(exist_helper(board, word, i, j-1, index+1))  
                return true;  
          
        if(j+1 < board[0].size() && board[i][j+1] == word[index+1])  
            if(exist_helper(board, word, i, j+1, index+1))  
                return true;  
          
        //匹配不成功,需要恢复原来的字母  
        board[i][j] = ctmp;  
        return false;  
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值