Leetcode79 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.

Example:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search

代码实现

class Solution {
public:
    bool existCore(vector<vector<char>>& board, string &word,int & Wordpos,int rows,int cols,int row,int col,vector<vector<int> > & visited){
        if(Wordpos>=word.size())
            return true;
        if(col>=cols||row>=rows||col<0||row<0){
            return false;
        }
        bool flag=false;
        if(board[row][col]==word[Wordpos]&& visited[row][col]!=1){
           ++Wordpos;
 visited[row][col]=1;           
            flag=existCore(board,word,Wordpos,rows,cols,row+1,col,visited)||existCore(board,word,Wordpos,rows,cols,row,col+1,visited)||existCore(board,word,Wordpos,rows,cols,row-1,col,visited)||existCore(board,word,Wordpos,rows,cols,row,col-1,visited);
            if(!flag)
            {
                --Wordpos;
                visited[row][col]=0;
            }
        }
        return flag;
    }
    bool exist(vector<vector<char>>& board, string word) {
        bool result=false;
        if(board.size()==0||board[0].size()==0){
            return false;
        }
        int rows=board.size();
        int cols=board[0].size();
        vector<vector<int> > visited;
        for(int i=0;i<rows;++i){
            vector<int> temp;
            for(int j=0;j<cols;++j){
                temp.push_back(0);
            }
            visited.push_back(temp);
        }
        int Wordpos=0;
        for(int i=0;i<rows;++i){
            for(int j=0;j<cols;++j)
            {
                if(existCore(board,word,Wordpos,rows,cols,i,j,visited))
                    return true;
            }
        }
        return false;
    }
};

总结

思路就是回溯法。中间纠结了一下,visited的数组是用二维数组还是用vector。后来发现如果用二维数组,传指针的地方较为麻烦,而且不能像vector一样直接visited[row][col]。

转载于:https://www.cnblogs.com/HaoPengZhang/p/11587327.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值