while (!q.empty()) { Node cur = q.front(); q.pop(); for (int i = 0; i < 8; i++) { int nx = cur.x + dx[i], ny = cur.y + dy[i]; if (nx < 1 || nx > n || ny < 1 || ny > m || dist[nx][ny] != -1) continue; dist[nx][ny] = dist[cur.x][cur.y] + 1; q.push({nx, ny}); } }
然后我们就完成了对所有情况的遍历,接着对答案进行输出
1 2 3 4
for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) cout << left << setw(5) << dist[i][j]; cout << '\n'; }
#include<bits/stdc++.h> usingnamespace std; using i32 = int32_t; using i64 = int64_t; using i128 = __int128_t; using u32 = uint32_t; using u64 = uint64_t; using u128 = __uint128_t;
int dist[401][401]; structNode { int x, y; }; int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2}; int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1};
int32_tmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, sx, sy; cin >> n >> m >> sx >> sy; memset(dist, -1, sizeof(dist)); queue<Node> q; dist[sx][sy] = 0; q.push({sx, sy}); while (!q.empty()) { Node cur = q.front(); q.pop(); for (int i = 0; i < 8; i++) { int nx = cur.x + dx[i], ny = cur.y + dy[i]; if (nx < 1 || nx > n || ny < 1 || ny > m || dist[nx][ny] != -1) continue; dist[nx][ny] = dist[cur.x][cur.y] + 1; q.push({nx, ny}); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) cout << left << setw(5) << dist[i][j]; cout << '\n'; } return0; }
/* Fufffh */ #include<bits/stdc++.h> usingnamespace std; using i32 = int32_t; using i64 = int64_t; using i128 = __int128_t; using u32 = uint32_t; using u64 = uint64_t; using u128 = __uint128_t;
structNode { int x, y; }; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1};
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); int h, w, d; cin >> h >> w >> d; vector<string> s(h); for (string &row : s) cin >> row; vector<vector<int>> dist(h, vector<int>(w, -1)); queue<Node> q; int ans = 0; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (s[i][j] == 'H') { dist[i][j] = 0; q.push({i, j}); ans++; } while (!q.empty()) { auto [x, y] = q.front(); q.pop(); if (dist[x][y] == d) continue; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= h || ny < 0 || ny >= w || s[nx][ny] == '#' || dist[nx][ny] != -1) continue; dist[nx][ny] = dist[x][y] + 1; q.push({nx, ny}); ans++; } } cout << ans << '\n'; return0; }