忍者小贝的追捕任务:最少查克拉能量消耗的影分身策略
#include "iostream"\n#include "vector"\n#include "queue"\n#include "climits"\nusing namespace std;
struct Node {
int x;
int y;
int cost;
Node(int x, int y, int cost) : x(x), y(y), cost(cost) {}
};
bool isValid(int x, int y, int n, int m) {
return (x >= 0 && x < n && y >= 0 && y < m);
}
int bfs(vector<vector
vector<vector
cost[startX][startY] = 0;
queue
q.push(Node(startX, startY, 0));
while (!q.empty()) {
Node curr = q.front();
q.pop();
int x = curr.x;
int y = curr.y;
int currCost = curr.cost;
if (grid[x][y] == 'O') {
return currCost;
}
vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (auto dir : directions) {
int newX = x + dir.first;
int newY = y + dir.second;
if (isValid(newX, newY, n, m) && grid[newX][newY] != '#' && currCost + 1 < cost[newX][newY]) {
cost[newX][newY] = currCost + 1;
q.push(Node(newX, newY, currCost + 1));
}
}
}
return -1;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector
int startX = -1, startY = -1;
int numX = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
if (grid[i][j] == 'X') {
numX++;
if (startX == -1 && startY == -1) {
startX = i;
startY = j;
}
}
}
}
int result = bfs(grid, startX, startY, n, m);
cout << numX << " " << result << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pEhP 著作权归作者所有。请勿转载和采集!