P1135 奇怪的电梯 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int id, step;
};
int main() {
int N, A, B;
cin >> N >> A >> B;
int K[205];
for (int i = 1; i <= N; ++i) {
cin >> K[i];
}
bool vis[205] = {false};
queue<Node> q;
q.push({A, 0});
vis[A] = true;
while (!q.empty()) {
Node x = q.front();
q.pop();
if (x.id == B) {
cout << x.step << endl;
return 0;
}
if (x.id + K[x.id] <= N && !vis[x.id + K[x.id]]) {
q.push({x.id + K[x.id], x.step + 1});
vis[x.id + K[x.id]] = true;
}
if (x.id - K[x.id] >= 1 && !vis[x.id - K[x.id]]) {
q.push({x.id - K[x.id], x.step + 1});
vis[x.id - K[x.id]] = true;
}
}
cout << -1 << endl;
return 0;
}
P1443 马的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <iostream>
#include <queue>
using namespace std;
struct Point {
int x, y, step;
};
int main() {
int n, m, x, y;
cin >> n >> m >> x >> y;
const int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2};
const int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1};
int chessboard[205][205];
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
chessboard[i][j] = -1;
}
}
queue<Point> q;
q.push({x, y, 0});
chessboard[x][y] = 0;
while (!q.empty()) {
Point current = q.front();
q.pop();
for (int k = 0; k < 8; ++k) {
int nx = current.x + dx[k];
int ny = current.y + dy[k];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && chessboard[nx][ny] == -1) {
q.push({nx, ny, current.step + 1});
chessboard[nx][ny] = current.step + 1;
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cout << chessboard[i][j] << ' ';
}
cout << endl;
}
return 0;
}