Word Search--Leetcode

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.


Basic ideas:

1. Perform an in-depth search of each point on the board.

2. Traditional ASCII code, only use 7bit, the highest bit is 0. Therefore, this bit can be used as the access flag bit.



Class Solution {Public:bool exist (vector<vector<char> > &board, String Word) {if (Board.empty ( ) ||                Board[0].empty ()) return false; for (int i=0; I<board.size (), i++) {for (int j=0; j<board[0].size (); j + +) {if (exist (boa            Rd, Word, 0, I, j)) return true;    }} return false;        } bool Exist (vector<vector<char> >&board, const string &word, int index, int x, int y) {        if (index = = word.size ()) return true;        if (x<0 | | y<0 | | x==board.size () | | y==board[0].size ()) return false;                if (board[x][y]! = Word[index]) return false;        Board[x][y] ^= 128;                             const BOOL existed = exist (board, Word, index+1, X, y+1) | |                             exist (board, Word, index+1, X, y-1) | |                             exist (board, Word, index+1, x+1, y) | | exist (board, Word, index+1, x-1, y);                Board[x][y] ^= 128;    return existed; }};


Word Search--Leetcode

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.