leetcode Word Search

来源:互联网 发布:淘宝的支付方式 编辑:程序博客网 时间:2024/06/14 00:26

我的第一次代码 85/87 那aaaaa的数据没过 哎难受    后面一点点的看 优化了一下 然后 勉强ac

class Solution {
public:
    vector<pair<int, int>> walk{{1,0},{-1,0},{0,1},{0,-1}};
    bool isExist(vector<vector<char>> board,string word,vector<vector<bool>> &used,int x,int y,int l)
    {    // x,y为末尾已经的到达坐标
        if(l>word.size()-1||word.size()==0)
            return true;
        bool flag=false;
        bool bb[4]={false};
        for(int i=0;i<=walk.size()-1;i++)
        {
            int newx=x+walk[i].first;
            int newy=y+walk[i].second;
           if(newx>=0&&newx<=board.size()-1&&newy>=0&&newy<=board[0].size()-1&&board[newx][newy]==word[l]&&used[newx][newy]==0)
           {
               flag=true;
               used[newx][newy]=1;
               bb[i]=isExist(board, word, used, newx, newy,l+1);
               used[newx][newy]=0;
               if(bb[i]==true)        //加了这两行就ac ,没加就超时,以后还是要好好优化 能省时间则省
                   return bb[i];
           }
        }
        return bb[0]||bb[1]||bb[2]||bb[3];
    }
    bool exist(vector<vector<char>>& board, string word) {
        vector<vector<bool>> used;
        vector<bool> b;
        for(int i=0;i<=board[0].size()-1;i++)
            b.push_back(false);
        for(int i=0;i<=board.size()-1;i++)
            used.push_back(b);
        string newone=word.substr(1);
        for(int i=0;i<=board.size()-1;i++)
            for(int j=0;j<=board[0].size()-1;j++)
                if(board[i][j]==word[0])
                {
                    used[i][j]=1;
                    if(isExist(board, newone, used, i, j,0))
                        return true;
                    used[i][j]=0;
                }
        return false;
    }
};


这是discuss上的一个老哥的解法:标题是my 19ms c++ 解法

我贴过来一下 纪录以后再看

https://leetcode.com/problems/word-search/discuss/

classSolution {public:boolexist(vector<vector<char> > &board, string word){ m=board.size(); n=board[0].size();for(int x=0;x<m;x++)for(int y=0;y<n;y++) { if(isFound(board,word.c_str(),x,y))returntrue; } returnfalse; } private:int m; int n; boolisFound(vector<vector<char> > &board, const char* w, int x,int y) {if(x<0||y<0||x>=m||y>=n||board[x][y]=='\0'||*w!=board[x][y])returnfalse;if(*(w+1)=='\0')returntrue;char t=board[x][y]; board[x][y]='\0';if(isFound(board,w+1,x-1,y)||isFound(board,w+1,x+1,y)||isFound(board,w+1,x,y-1)||isFound(board,w+1,x,y+1))returntrue; board[x][y]=t; returnfalse; } };

原创粉丝点击