[LeetCode]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 are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example, Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

思考:DFS。若存在多个word,找到一个就可以return了,不然TLE。

class Solution {
private:
	bool visit[100][100];
	bool flag;
public:
	void DFS(bool &flag,vector<vector<char> > board,string word,int i,int j,int dep)
	{
		if(flag) return;
		if(dep==word.size()) {flag=true;return;}
		visit[i][j]=true;
		if(j<board[0].size()-1&&board[i][j+1]==word[dep]&&!visit[i][j+1]) DFS(flag,board,word,i,j+1,dep+1);
		if(i<board.size()-1&&board[i+1][j]==word[dep]&&!visit[i+1][j]) DFS(flag,board,word,i+1,j,dep+1);	
		if(j>0&&board[i][j-1]==word[dep]&&!visit[i][j-1]) DFS(flag,board,word,i,j-1,dep+1);
		if(i>0&&board[i-1][j]==word[dep]&&!visit[i-1][j]) DFS(flag,board,word,i-1,j,dep+1);	
		visit[i][j]=false;
	}
    bool exist(vector<vector<char> > &board, string word) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		int row=board.size();
		int line=board[0].size();
		int i,j;
		memset(visit,0,sizeof(visit));
		for(i=0;i<row;i++)
		{
			for(j=0;j<line;j++)
			{
				flag=false;
				if(board[i][j]==word[0]) 
				{
					DFS(flag,board,word,i,j,1);
					if(flag) return flag;
				}
			}
		}
		return flag;
    }
};

  

原文地址:https://www.cnblogs.com/Rosanna/p/3432146.html