We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
int minimumMoves(vector grid, int startX, int startY, int goalX, int goalY) {
int n = grid.size();
vector> visited(n, vector(n, false));
queue q;
q.push({startX, startY, 0});
visited[startX][startY] = true;
int dx[] = {-1, 1, 0, 0}; // up, down
int dy[] = {0, 0, -1, 1}; // left, right
while (!q.empty()) {
Node curr = q.front();
q.pop();
if (curr.x == goalX && curr.y == goalY)
return curr.moves;
for (int dir = 0; dir < 4; ++dir) {
int nx = curr.x;
int ny = curr.y;
while (true) {
nx += dx[dir];
ny += dy[dir];
if (nx < 0 || ny < 0 || nx >= n || ny >= n || grid[nx][ny] == 'X')
break;
if (!visited[nx][ny]) {
visited[nx][ny] = true;
q.push({nx, ny, curr.moves + 1});
}
}
}
}
return -1; // should never reach here if input guarantees a path
}
int main() {
int n;
cin >> n;
vector grid(n);
for (int i = 0; i < n; ++i)
cin >> grid[i];
Castle on the Grid
You are viewing a single comment's thread. Return to all comments →
include
include
include
using namespace std;
struct Node { int x, y, moves; };
int minimumMoves(vector grid, int startX, int startY, int goalX, int goalY) { int n = grid.size(); vector> visited(n, vector(n, false)); queue q; q.push({startX, startY, 0}); visited[startX][startY] = true;
}
int main() { int n; cin >> n; vector grid(n); for (int i = 0; i < n; ++i) cin >> grid[i];
return 0; }