美文网首页
LeetCode 16-12-20 Word Search

LeetCode 16-12-20 Word Search

作者: Cheong_Hoo | 来源:发表于2016-12-20 19:37 被阅读0次

    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,
    Givenboard=
    [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
    ]
    word="ABCCED", -> returnstrue,
    word="SEE", -> returnstrue,
    word="ABCB", -> returnsfalse.

        public:
             bool exist(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))
                            return true;
                    }
                return false;
            }
        private:
            int m;
            int n;
            bool isFound(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])
                    return false;
                if(*(w+1)=='\0')
                    return true;
                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))
                    return true; 
                board[x][y]=t;
                return false;
            }
        };```
    

    相关文章

      网友评论

          本文标题:LeetCode 16-12-20 Word Search

          本文链接:https://www.haomeiwen.com/subject/pxjfvttx.html