123. Word Search (DFS)

Source: Internet
Author: User

Describe

Give a two-dimensional letter board and a word to find out if the word is present in the letter Board grid.
Words can consist of the letters of adjacent cells in order, in which adjacent cells refer to the horizontal or vertical direction adjacent. The letters in each cell can be used at most once.

Sample Example

Give the
board =
[
"ABCe",
"SFCs",
"Adee"]

Word = "abcced", and returns True,
Word = "See",-> returns True,
Word = "ABCB", and returns false.

Class Solution {public:/** * @param board:a List of lists of character * @param word:a String * @return:  A Boolean */bool exist (vector<vector<char>> &board, string &word) {//write your code Here/write your code here vector< vector<bool> > Mask (board.size (), VECTOR&LT;BOOL&G        t; (Board[0].size (), false)); for (int i=0; I<board.size (), ++i) {for (int j=0; j<board[0].size (); ++j) {if (Search (bo                ARD, Word, mask, I, J, 0)) {return true;    }}} return false; } bool Search (vector< vector<char> >& Board, String Word, vector< vector<bool> >& m            Ask, int i, int j, int idx) {if (Word[idx]==board[i][j]) {mask[i][j] = true;            ++idx;            if (idx = = Word.size ()) return true; else if (i-1>=0 &&!mask[i-1][j] &&Search (board, Word, Mask, i-1, J, IDX)) return true;            else if (i+1< board.size () &&!mask[i+1][j] && Search (board, Word, Mask, i+1, J, IDX)) return true;            else if (j-1>=0 &&!mask[i][j-1]&& Search (board, Word, mask, I, j-1, idx)) return true; else if (j+1< board[0].size () &&!mask[i][j+1] && Search (board, Word, mask, I, j+1, idx)) return            True                else {Mask[i][j] = false;            return false; }        }    }};

123. Word Search (DFS)

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.