[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 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.

Ideas:
The DFS approach is similar to solving the maze problem.
1) Find the beginning of the entrance, here is to find and value word[0] the same position
2) Start recursive lookup, Word[1],word[2]....word[word.size ()-1], and solve the maze problem, here is the requirement of adjacent lattice, so the upper and lower left and right four directions to find a suitable solution.
3) if Cur=word.size (), the representative has found all the characters of this word, returns success. The algorithm ends.

classSolution { Public:BOOLvisited[ -][ -];intstep[4][2];voidDfsintXintYintCurintLenstring&word, vector<vector<char> >&board,BOOL&flag) {if(flag)return;if(cur = = len) {flag =true;return; } for(intI=0;i<4; i++) {inttx = x + step[i][0];intty = y + step[i][1];if(TX >=0&& TX < Board.size () && ty >=0&& Ty < board[0].size () && (visited[tx][ty] = =false) && Board[tx][ty] = = Word[cur]) {Visited[tx][ty] =true; DFS (tx,ty,cur+1, Len,word,board,flag); Visited[tx][ty] =false; }        }    }voidInit () {memset(Visited,false,sizeof(visited)); step[0][0] =1; step[0][1] =0; step[1][0] = -1; step[1][1] =0; step[2][0] =0; step[2][1] =1; step[3][0] =0; step[3][1] = -1; }BOOLExist vector<vector<char> >&board,stringWord) {intI,j;if(word.size () = =0)return true; Init (); for(i=0; I<board.size (); i++) { for(j=0; j<board[0].size (); j + +) {if(board[i][j]==word[0]){BOOLFlag =false; VISITED[I][J] =true; DFS (I,J,1, Word.size (), Word,board,flag);if(flag)return true; VISITED[I][J] =false; }            }            }return false; }};

[Leetcode] Word Search

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.