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> ds = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector> visited(n, vector(n, false));
queue<pair<int, int>> q;
q.push({startX, startY});
visited[startX][startY] = true;
int step = 0;
while (!q.empty()) {
int length = q.size();
++step;
for (int i = 0; i < length; ++i) {
pair<int, int> curr = q.front();
q.pop();
for (const auto& d : ds) {
int newX = curr.first;
int newY = curr.second;
while (!(newX < 0 || newX >= n || newY < 0 || newY >= n || grid[newX][newY] == 'X')) {
if (newX == goalX && newY == goalY) {
return step;
}
if (!visited[newX][newY]) {
q.push({newX, newY});
visited[newX][newY] = true;
}
newX += d[0];
newY += d[1];
}
}
}
}
return -1;
}
int main() {
int n;
cin >> n;
vector<string> grid(n);
for (int i = 0; i < n; ++i) {
cin >> grid[i];
}
int startX, startY, goalX, goalY;
cin >> startX >> startY >> goalX >> goalY;
int result = minimumMoves(grid, startX, startY, goalX, goalY);
cout << result << endl;
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Castle on the Grid
You are viewing a single comment's thread. Return to all comments →
include
include
include
using namespace std;
int minimumMoves(vector& grid, int startX, int startY, int goalX, int goalY) { int n = grid.size(); vector> ds = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector> visited(n, vector(n, false));
}
int main() { int n; cin >> n;
}