題意:給一 m x n 的網格 board 和一 string word, 求 word 是否出現在 board 中。
其中, board 和 word 僅由大小寫英文字母所組成
注意:必須按照 word 中字母的順序, 並通過相鄰的 cell 所構成, 其中相鄰是指水平相鄰 or 垂直相鄰, 且同一位置的 cell 不允許被重複使用。
Solution:
想法:利用 DFS, 要記得將已拜訪過的 node 設為已拜訪, 避免重複拜訪
classSolution { public: boolexist(vector<vector<char>>& board, string word){ m = board.size(), n = board[0].size();
// 依序把 board[i][j] 作為起始點來探索 for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (dfs(board, i, j, word, 0)) { returntrue; } } } returnfalse; }
private: int m, n; vector<pair<int, int>> dirs = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
booldfs(vector<vector<char>>& board, constint i, constint j, const string& word, constint idx){ if (outOfBound(i, j) || board[i][j] != word[idx]) { returnfalse; }
// word 的最後一個 char 有被找到(前面的也都有被找到, idx 才會執行到最後一個) if (idx == word.size() - 1) { returntrue; }