这是一个经典的路径搜索问题,需要在给定的字母矩阵中寻找连续的"candy"路径。以下是C++实现代码: ```cpp #include <iostream> #include <vector> #include <string> #include <utility> using namespace std; const string TARGET = "candy"; const int MAX_STEPS = 5; const int DIRECTIONS[8][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1}}; bool dfs(const vector<string>& grid, vector<pair<int,int>>& path, int step, int x, int y) { if (step == MAX_STEPS) { return true; } for (const auto& dir : DIRECTIONS) { int nx = x + dir[0]; int ny = y + dir[1]; if (nx >= 0 && nx < grid.size() && ny >= 0 && ny < grid[0].size() && grid[nx][ny] == TARGET[step]) { path[step] = {nx, ny}; if (dfs(grid, path, step + 1, nx, ny)) { return true; } } } return false; } int main() { int N, M; cin >> N >> M; vector<string> grid(N); for (int i = 0; i < N; ++i) { cin >> grid[i]; } vector<pair<int,int>> path(MAX_STEPS); bool found = false; // 遍历所有可能的起点 for (int i = 0; i < N && !found; ++i) { for (int j = 0; j < M && !found; ++j) { if (grid[i][j] == TARGET[0]) { path[0] = {i, j}; if (dfs(grid, path, 1, i, j)) { found = true; } } } } if (found) { for (const auto& p : path) { cout << p.first + 1 << " " << p.second + 1 << endl; } } else { cout << "No path found" << endl; } return 0; } ``` 代码说明: 1. 使用深度优先搜索(DFS)来寻找路径 2. 从每个可能的起点(字母'c')开始搜索 3. 每次移动可以朝8个方向中的任意一个 4. 路径必须连续匹配"c"→"a"→"n"→"d"→"y" 5. 输出找到的第一条有效路径(行号和列号从1开始) 注意: - 如果存在多条路径,此代码只输出找到的第一条 - 如果没有找到路径,会输出"No path found" - 行号和列号从1开始计数,与常见的编程习惯不同 [2025-05-16 16:50:18 | AI问答 | 659点数解答]