给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true 给定 word = "SEE", 返回 true 给定 word = "ABCB", 返回 false
提示:
board
和word
中只包含大写和小写英文字母。1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
解答(C++):
class Solution { public: bool en; bool backTrace(vector<vector<char>>& board, int i, int j, string& word, int index) { if (board[i][j] != word[index]) return false; if (index == word.size() -1) return true; char tmp = board[i][j]; board[i][j] = 0; index++; if ( (i > 0 && backTrace(board, i-1, j, word, index)) //上 ||(j > 0 && backTrace(board, i, j-1, word, index)) //左 ||(i < board.size()-1 && backTrace(board, i+1, j, word, index)) //下 ||(j < board[0].size()-1 && backTrace(board, i, j+1, word, index)) //右 ) { return true; } board[i][j] = tmp; return false; } bool exist(vector<vector<char>>& board, string word) { if (board.empty()) return false; for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { if (backTrace(board, i, j, word, 0)) { return true; } } } return false; } };
来源:https://www.cnblogs.com/vczf/p/12617655.html