P1443 馬的遍歷
阿新 • • 發佈:2022-03-27
題目連結
題目思路
經典寬搜問題,記住馬走日!
題目程式碼
#include <iostream> #include <algorithm> #include <cstring> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 410; bool st[N][N]; int dist[N][N]; int n, m; void bfs(int x, int y) { queue<PII> q; q.push({x, y}); dist[x][y] = 0; st[x][y] = true; while(q.size()) { auto t = q.front(); q.pop(); int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1}, dy[8] = {2, 1, -1, -2, 2, 1, -1, -2}; for(int i = 0; i < 8; i ++) { int a = t.first + dx[i], b = t.second + dy[i]; if(a >= 1 && a <= n && b >= 1 && b <= m && !st[a][b]) { dist[a][b] = dist[t.first][t.second] + 1; st[a][b] = true; q.push({a, b}); } } } } int main() { int x, y; printf("%d%d%d%d", &n, &m, &x, &y); memset(dist, -1, sizeof dist); bfs(x, y); for(int i = 1; i <= n; i ++ ) { for(int j = 1; j <= m; j ++ ) printf("%-5d", dist[i][j]); puts(""); } return 0; }