Leetcode 79 Word Search

通过这道题目,加深了对backtracking的理解。

其实,就像武侠小说中说的,手中无剑,心中有剑。backtracking本来没有什么模式可言,题目不同,条件不同,那么程序自然也就不一样。当然在很多典型情况下还是有模板的,但是,本题却不好利用模板。没有显而易见的isValid函数,当然该递归还是递归的。

那么真正以不变应万变的是什么?丰富的经验,明确的思路,大概才是王道吧。


class Solution
{
public:
	bool existHelper(vector<vector<char> > &board, string word, int row,
			int column)
	{
		int row_max = board.size() - 1;
		int column_max = board[0].size() - 1;
		if (word.empty())
			return true; //edge case, we have found all the word
		if (row > 0 && board[row - 1][column] == word[0])
		{
			char temp = word[0]; //save the char
			board[row - 1][column] = ' ';
			if (existHelper(board, word.substr(1), row - 1, column))
				return true;
			board[row - 1][column] = temp;
		}
		if (column != 0 && board[row][column - 1] == word[0])
		{
			char temp = word[0]; //save the char
			board[row][column - 1] = ' ';
			if (existHelper(board, word.substr(1), row, column - 1))
				return true;
			board[row][column - 1] = temp;
		}
		if (row < row_max && board[row + 1][column] == word[0])
		{
			char temp = word[0]; //save the char
			board[row + 1][column] = ' ';
			if (existHelper(board, word.substr(1), row + 1, column))
				return true;
			board[row + 1][column] = temp;
		}
		if (column < column_max && board[row][column + 1] == word[0])
		{
			char temp = word[0]; //save the char
			board[row][column + 1] = ' ';
			if (existHelper(board, word.substr(1), row, column + 1))
				return true;
			board[row][column + 1] = temp;
		}
		return false; //have tried all the possiblities

	}
	bool exist(vector<vector<char> > &board, string word)
	{
		if (word.empty())
			return true; //always true for empty word
		if (board.empty())
			return false; // always false if board is empty
		unsigned int row, column;
		for (row = 0; row < board.size(); row++)
			for (column = 0; column < board[0].size(); column++)
			{
				if (board[row][column] == word[0])
				{
					char temp = board[row][column];
					board[row][column] = ' '; //assign a temp blank to the position
					if (existHelper(board, word.substr(1), row, column))
						return true;
					board[row][column] = temp;
				}
			}
		return false; //cannot find the first element

	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值