本文共 1822 字,大约阅读时间需要 6 分钟。
为了解决这个问题,我们需要在一个网格迷宫中找到所有可以到达的格子。每次移动可以向上下左右移动一格,但向左移动的次数不能超过 x 次,向右移动的次数不能超过 y 次。我们可以使用广度优先搜索(BFS)来解决这个问题。
#include#include #include using namespace std;int main() { // 读取输入 int n, m; cin >> n >> m; int r, c; cin >> r >> c; r--; c--; // 转为0-based索引 int x, y; cin >> x >> y; char mp[n][m]; for (int i = 0; i < n; ++i) { string s; cin >> s; for (int j = 0; j < m; ++j) { mp[i][j] = s[j]; } } // 初始化访问数组和队列 bool visited[n][m]; queue > q; visited[r][c] = true; q.push(make_pair(r, c)); int sum = 1; // 起点计数 // 四个方向:上下左右 int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; while (!q.empty()) { pair current = q.front(); q.pop(); int i = current.first, j = current.second; for (int d = 0; d < 4; ++d) { int ni = i + dirs[d][0]; int nj = j + dirs[d][1]; // 检查是否越界 if (ni < 0 || ni >= n || nj < 0 || nj >= m) { continue; } // 检查是否是障碍 if (mp[ni][nj] != '.') { continue; } // 计算max_left和max_right int dr = ni - r; int dc = nj - c; int max_left = max(-dr, 0); int max_right = max(dc, 0); if (max_left <= x && max_right <= y) { if (!visited[ni][nj]) { visited[ni][nj] = true; sum++; q.push(make_pair(ni, nj)); } } } } cout << sum << endl; return 0; }
这种方法确保了我们高效地找到所有满足条件的格子,避免了不必要的计算和状态扩展。
转载地址:http://iuqjz.baihongyu.com/