//确定起点 for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[0].size(); j++) { if (word[0] == matrix[i][j]) { if (findPath(matrix, i, j, word, 0)) returntrue; } } } returnfalse; }
private: boolfindPath(vector<vector<char>>& matrix, int start_i, int start_j, string word, int index){ if (matrix[start_i][start_j] != word[index]) returnfalse; // 核心检查 if (index == word.length() - 1) returntrue;
bool found = false; if (start_i > 0) found = found || findPath(matrix, start_i - 1, start_j, word, index + 1); if (start_i < matrix.size() - 1) found = found || findPath(matrix, start_i + 1, start_j, word, index + 1); if (start_j > 0) found = found || findPath(matrix, start_i, start_j - 1, word, index + 1); if (start_j < matrix[0].size() - 1) found = found || findPath(matrix, start_i, start_j + 1, word, index + 1);