Leetcode: Word Search

来源:互联网 发布:58同城网络兼职招聘 编辑:程序博客网 时间:2024/04/26 14:52
class Solution {public:    bool exist(vector<vector<char> > &board, string word) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        for(int i=0;i<board.size();++i){            for(int j=0;j<board[0].size();++j){                if(board[i][j]==word[0]){                    vector<vector<char> > tmp(board);                    if(helper(tmp,i,j,word,0))                        return true;                }            }        }    }    bool helper(vector<vector<char> >& board,int i,int j,string& word,int index){        if(index==word.size())            return true;        if(i>=0&&i<board.size()&&j>=0&&j<board[0].size()&&word[index]==board[i][j]){            board[i][j]='*';            ++index;            return helper(board,i+1,j,word,index)||helper(board,i,j+1,word,index)||helper(board,i,j-1,word,index)||helper(board,i-1,j,word,index);        }        return false;    }};

原创粉丝点击