Leetcode79: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.

began to do questions about backtracking.

Basic Solution

The analysis of this problem is this:
For any element in the board, if it exists and is not accessed, then there are four search paths up, down, left, and right, then the search path is defined as a recursive function that needs to know the location of the search point and the remaining substrings in Word. The terminating condition for recursion is that the remaining substring in Word is empty.
Since each element in the board can be the starting point for recursion, you need to do a double loop on board, and for an element to be accessed, you can define a table mask that is the same size as board to indicate whether the element has been accessed, has been accessed to the corresponding value in mask is recorded as 1, based on the idea of the code is as follows:
Runtime:36

classSolution { Public:BOOLExist vector<vector<char>>& Board,stringWord) {intHeight=board.size ();if(height==0)return false;intwidth=board[0].size (); vector<vector<int> >Mask (height, vector<int>(Width,0));//0 indicates that the element is not being used         for(intI=0; i for(intj=0; j<width;j++) {if(Backtrack (Board,word,i,j,0, mask))return true; }        }return false; }//start looking for Word from node Board[i][j]    BOOLBacktrack vector<vector<char>>& Board,stringWordintIintJintPos vector<vector<int>>&mask) {intHeight=board.size ();intwidth=board[0].size ();if(board[i][j]!=word.at (POS))return false;if(Pos==word.size ()-1)return true; mask[i][j]=1;//Right        if(j+1<width&&mask[i][j+1]==0&&backtrack (board,word,i,j+1, pos+1, mask))return true;//Down        if(i+11][j]==0&&backtrack (board,word,i+1, j,pos+1, mask))return true;//Left        if(I-1>=0&&mask[i-1][j]==0&&backtrack (board,word,i-1, j,pos+1, mask))return true;//Up        if(J-1>=0&&mask[i][j-1]==0&&backtrack (board,word,i,j-1, pos+1, mask))return true; mask[i][j]=0;return false; }};
Optimize a

Then look at the discussion in discuss and find that you can omit the mask and use the board directly, because the previous value can be restored with each step backtracking.
Runtime:36ms

classSolution { Public:BOOLExist vector<vector<char>>& Board,stringWord) {intHeight=board.size ();if(height==0)return false;intwidth=board[0].size (); for(intI=0; i for(intj=0; j<width;j++) {if(Backtrack (Board,word,i,j,0))return true; }        }return false; }//start looking for Word from node Board[i][j]    BOOLBacktrack vector<vector<char>>& Board,stringWordintIintJintPOS) {intHeight=board.size ();intwidth=board[0].size ();if(board[i][j]!=word.at (POS))return false;if(Pos==word.size ()-1)return true;intC=BOARD[I][J]; board[i][j]="';//Right        if(j+1<width&&board[i][j+1]!="'&&backtrack (board,word,i,j+1, pos+1))return true;//Down        if(i+11][j]!="'&&backtrack (board,word,i+1, j,pos+1))return true;//Left        if(I-1>=0&&board[i-1][j]!="'&&backtrack (board,word,i-1, j,pos+1))return true;//Up        if(J-1>=0&&board[i][j-1]!="'&&backtrack (board,word,i,j-1, pos+1))return true; Board[i][j]=c;return false; }};
Optimize two

The code can then be further optimized, since there is no access to the next value in the four-direction search process but simply passing parameters to the function, so you can place the discussion of the boundary value at the entrance of the function and merge the search in four directions.
Runtime:24ms

classSolution { Public:BOOLExist vector<vector<char>>& Board,stringWord) {intHeight=board.size ();if(height==0)return false;intwidth=board[0].size (); for(intI=0; i for(intj=0; j<width;j++) {if(Backtrack (Board,word,i,j,0))return true; }        }return false; }//start looking for Word from node Board[i][j]    BOOLBacktrack vector<vector<char>>& Board,string& Word,intIintJintPOS) {intHeight=board.size ();intwidth=board[0].size ();if(i<0|| j<0|| i>=height| | j>=width| | board[i][j]==' + '|| Board[i][j]!=word[pos])return false;if(Pos==word.size ()-1)return true;CharT=BOARD[I][J]; board[i][j]=' + ';if(Backtrack (board,word,i,j+1, pos+1)|| Backtrack (board,word,i+1, j,pos+1)|| Backtrack (board,word,i-1, j,pos+1)|| Backtrack (board,word,i,j-1, pos+1))return true; board[i][j]=t;return false; }};}

This is the beginning of the system to do the retrospective problem of the first question, spend more time, but the understanding of the problem is also more thorough, do this problem is not the beginning of the word's subscript location but the substring, the result starts to show time-out, so you need to pay attention to this detail in the later processing of the string, There is a mask problem, this mask can be analyzed with such a problem is easier to analyze, but when writing code to see if you can omit the function in the existing parameters to replace. The problem can be omitted instead of using board directly, thus saving space.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode79: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.