1. Unbounded Standard BFS
Intuition
Queue states (r, c) starting at (0, 0). At each step, expand all 8 knight moves. Mark visited coordinates in a hash set. The first time (x, y) is popped from the queue, return the current step count.
Algorithm
- If x == 0 && y == 0, return 0.
- Initialize queue with (0, 0) and visited set containing
(0,0). - steps = 0.
- While queue is not empty:
- levelSize = queue.size.
- Loop levelSize times:
- Pop (r, c).
- If r == x && c == y, return steps.
- For 8 moves (dr, dc):
- nr = r + dr, nc = c + dc.
- If '(nr, nc)' not visited:
- Mark visited and push to queue.
- steps++.
- Return steps.
#include <iostream>#include <vector>#include <queue>#include <unordered_set>#include <string> class Solution {public: int minKnightMoves(int x, int y) { if (x == 0 && y == 0) return 0; std::queue<std::pair<int, int>> q; std::unordered_set<std::string> visited; q.push({0, 0}); visited.insert("0,0"); int dr[] = {-2, -2, -1, -1, 1, 1, 2, 2}; int dc[] = {-1, 1, -2, 2, -2, 2, -1, 1}; int steps = 0; while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; ++i) { auto [r, c] = q.front(); q.pop(); if (r == x && c == y) return steps; for (int k = 0; k < 8; ++k) { int nr = r + dr[k], nc = c + dc[k]; std::string key = std::to_string(nr) + "," + std::to_string(nc); if (!visited.count(key)) { visited.insert(key); q.push({nr, nc}); } } } steps++; } return steps; }}; int main() { Solution sol; std::cout << "Unbounded BFS (2, 1): " << sol.minKnightMoves(2, 1) << " (Expected: 1)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(8^d) - Space complexity:
O(8^d)