LeetCode79: word search, and the importance of passing a reference at the time of mass participation

Given a two-dimensional grid and a word, to find out whether the word exists in the grid.

Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.

Example:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

Given word = "ABCCED", returns true.
Given word = "SEE", returns true.
Given word = "ABCB", returns false.

The title is actually a very simple subject, DFS + back enough, but the beginning of a version of the running time is always in the presence of three sample timeout:

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
		if(word.size()==0)
			return false;
		for(int row=0;row<board.size();row++)
		{
			for(int col=0;col<board[row].size();col++)
			{
				if(Core(board,word,0,row,col))
					return true;
			}
		}
		return false;
    }
	bool Core(vector<vector<char>>& dict,string word,int pos,int row,int col)
	{
		if(pos==word.size())
			return true;
		if(row<0||row>=dict.size()||col<0||col>=dict[row].size()
			||dict[row][col]!=word[pos])
			return false;
		dict[row][col]='#';
		if(Core(dict,word,pos+1,row-1,col)||Core(dict,word,pos+1,row+1,col)
			||Core(dict,word,pos+1,row,col-1)||Core(dict,word,pos+1,row,col+1))
			return true;
		return false;
	}
};

  This version of backtracking actually rely on the characteristic values ​​of the parameters passed to each time transfer matrix in, modify a copy of the matrix instead of the original matrix, also led to a timeout, because every time we pass a re-construction matrix.

The following version will use the passing references, backtracking rely on the use of temporary variables to save himself after using the modified modified back.

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
		if(word.size()==0)
			return false;
		for(int row=0;row<board.size();row++)
		{
			for(int col=0;col<board[row].size();col++)
			{
				if(Core(board,word,0,row,col))
					return true;
			}
		}
		return false;
    }
	bool Core(vector<vector<char>>& dict,string& word,int pos,int row,int col)
	{
		if(pos==word.size())
			return true;
		if(row<0||row>=dict.size()||col<0||col>=dict[row].size()
			||dict[row][col]!=word[pos])
			return false;
		char tmp=dict[row][col];
		dict[row][col]='#';
		if(Core(dict,word,pos+1,row-1,col)||Core(dict,word,pos+1,row+1,col)
			||Core(dict,word,pos+1,row,col-1)||Core(dict,word,pos+1,row,col+1))
			return true;
		dict[row][col]=tmp;
		return false;
	}
};

  After dict and word are used in passing references, beyond the 99% of the time complexity, and the original sample have a timeout on the sample.

In this high complexity of the topic, the use pass by reference is really important

Guess you like

Origin www.cnblogs.com/lxy-xf/p/11301923.html