Leetcode 79 Word Search

来源:互联网 发布:mac os x iso 下载 编辑:程序博客网 时间:2024/04/25 18:34

通过这道题目,加深了对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 wordif (row > 0 && board[row - 1][column] == word[0]){char temp = word[0]; //save the charboard[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 charboard[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 charboard[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 charboard[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 wordif (board.empty())return false; // always false if board is emptyunsigned 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 positionif (existHelper(board, word.substr(1), row, column))return true;board[row][column] = temp;}}return false; //cannot find the first element}};


原创粉丝点击