# [Leetcode] Word Search

Source: Internet
Author: User

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 is those horizontally or V Ertically neighboring. The same letter cell is used more than once.

For example,
Given Board =

`[  ["ABCE"],  ["SFCs"],  ["Adee"]]`
Word= `"ABCCED"`, returns `true`,
Word= `"SEE"`, returns `true`,
Word= `"ABCB"`, returns `false`. Idea: DFS algorithm. Note: Because each character can only match once, the match succeeds in placing the character as a useless character, such as ' # ', and then continues to match the next character.
`classsolution{ Public: Solution (): IsTrue (false) {}Private:  voidDFS (vector<vector<Char> > &board,stringWordintXintYintindex) {    if(Index = =word.size ()) {IsTrue=true; return; }        if(isTrue)return; if(X <0|| x >= board.size ())return; if(Y <0|| Y >= board[0].size ())return; if(Board[x][y]! = Word[index])return; Board[x][y]='#'; DFS (board, Word, x-1, Y, index+1); DFS (board, Word, x+1, Y, index+1); DFS (board, Word, x, y-1, index+1); DFS (board, Word, x, y+1, index+1); Board[x][y]=Word[index]; } Public:  BOOLexist (vector<vector<Char> > &board,stringword) {    if(Board.empty () | | board[0].empty ())return false; IsTrue=false; intindex =0;  for(intI=0; I<board.size (); i++)    {       for(intj=0; j<board[0].size (); J + +)      {        if(!isTrue) DFS (board, Word, I, J, index); }    }    returnisTrue; }Private:  BOOLisTrue;};`

[Leetcode] Word Search

Related Keywords:

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.