LeetCode OJ 之 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.

给定一个2维板和一个单词,确定在这个板中是否存在这个单词。

单词可以由连续相邻单元的字母组成。相邻单元指的是上下左右相邻。相同的字母不能使用超过一次。

For example,
Given board =

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

思路:

基本思路就是从某一个元素出发,往上下左右进行深度搜索。判断是否有等于word的字符串。这里因为要求相同的字母不能使用超过一次,因此需要用个bool型变量标记当前字母是否被标记过。

代码:

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word)
    {
        if(board.empty())
            return false;
        int row = board.size();
        int col = board[0].size();
        vector<vector<bool> > visited(row,vector<bool>(col,false));//标记深搜时当前字母是否判断过
        for(int i = 0 ; i < row ; i++)
        {
            for(int j = 0 ; j < col ; j++)
            {
                //从当前点board[i][j开始进行深搜
                if(dfs(board,word,0,i,j,visited))
                    return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char> > &board, string &word,int index,int i , int j,vector<vector<bool> > &visited)
    { 
        //index到达word最后,说明找到了符合的
        if(index == word.size())
            return true;
        if(i<0 || j<0 || i>=board.size() || j>= board[0].size())
            return false;
        //如果当前字母被访问过
        if(visited[i][j])
            return false;
        //当前字母不符合条件
        if(word[index] != board[i][j])
            return false;
        //以上都不满足,说明当前字母符合条件,置为true,继续对当前单词的上下左右深搜
        visited[i][j] = true;
        bool ret = dfs(board,word,index+1,i-1,j,visited) || 
                   dfs(board,word,index+1,i+1,j,visited) || 
                   dfs(board,word,index+1,i,j-1,visited) || 
                   dfs(board,word,index+1,i,j+1,visited);
        //从board[i][j]点开始深搜完成后,visited要重置为false
        visited[i][j] = false;
        return ret;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值