Leetcode word search

Source: Internet
Author: User

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=

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]

Word="ABCCED",-> Returnstrue,
Word="SEE",-> Returnstrue,
Word="ABCB",-> Returnsfalse

This question can be searched in depth.

 

class Solution {public:    typedef vector<vector<bool> > VVB;    typedef vector<vector<char> > VVC;        const int dx[4] = {0,1,0,-1};    const int dy[4] = {1,0,-1,0};        int n,m;    VVC board;    string word;        bool dfs(int x, int y,int index,VVB &visit){        if(index == word.length()) return true;        if(x>=0 && x <n && y>=0 && y < m && !visit[x][y] && board[x][y] == word[index]){            visit[x][y] = true;            for(int i = 0 ; i < 4; ++ i){                if(dfs(x+dx[i], y+dy[i],index+1,visit)) return true;            }            visit[x][y] = false;        }        return false;    }    bool exist(VVC &board, string word) {        this->board = board;        this->word = word;        n = board.size();        m = board[0].size();        VVB visit(n,vector<bool>(m,false));        for(int i = 0 ; i < n; ++i ){            for(int j = 0 ; j < m ;++ j){                if(dfs(i,j,0,visit)) return true;            }        }        return false;    }};

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.