提交时间:2026-06-15 19:38:26
运行 ID: 91751
#include <iostream> #include <vector> #include <string> using namespace std; // 定义网格 const vector<string> grid = { "从我做起振", "做起振兴中", // 注意:题目描述中第二行是"我做起振兴",第三行"做起振兴中",第四行"起振兴中华" // 让我们重新仔细核对题目给出的网格: // 从我做起振 // 我做起振兴 // 做起振兴中 // 起振兴中华 }; // 修正网格数据 const vector<string> actual_grid = { "从我做起振", "我做起振兴", "做起振兴中", "起振兴中华" }; const string target = "从我做起振兴中华"; const int rows = 4; const int cols = 5; // 方向数组:上、下、左、右 const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; /** * 深度优先搜索 * @param x 当前行坐标 * @param y 当前列坐标 * @param index 当前需要匹配的目标字符串的索引 * @return 从当前位置开始能构成的合法路径数量 */ int dfs(int x, int y, int index) { // 如果当前字符不匹配,直接返回0 if (actual_grid[x][y] != target[index]) { return 0; } // 如果已经匹配到最后一个字符,说明找到一条完整路径 if (index == target.length() - 1) { return 1; } int count = 0; // 尝试四个方向 for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // 检查边界 if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) { // 递归搜索下一步,匹配下一个字符 count += dfs(nx, ny, index + 1); } } return count; } int main() { // 优化IO ios::sync_with_stdio(false); cin.tie(NULL); // 从左上角 (0,0) 开始,匹配第0个字符 '从' int result = dfs(0, 0, 0); cout << result << endl; return 0; }