阿里3.23日笔试第二题交流
阿里笔试第二题
给你一个迷宫,包括一个起点‘S’和一个终点‘E’,‘#’表示障碍,不可到达的位置,‘.'表示可以到达的位置,另外你可以跳跃,跳跃的规则是从一个点跳到他中心对称的那个点上,最多跳跃5次,求从起点到达终点的最短路径长度。
我用BFS写了个没有限制跳跃的版本
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int dir[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}};
int main() {
int n = 4;
int m = 4;
vector<vector<char>> grid {{'#', 'S', '.', '.'},
{'E', '#', '#', '.'},
{'#', '#', '#', '.'},
{'#', '#', '#', '.'}};
queue<vector<int>> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 'S') {
q.push({i, j, 0});
}
}
}
int depth = 0;
bool flag = false;
while (!q.empty()) {
auto index = q.front();
q.pop();
int x = index[0];
int y = index[1];
depth = index[2];
if (grid[x][y] == 'E') {
flag = true;
break;
}
grid[x][y] = '#';
for (int i = 0; i < 5; i++) {
int xx, yy;
if (i == 4) {
xx = n - 1 - x; // 中心对称跳跃
yy = m - 1 - y;
}
else {
xx = x + dir[i][0];
yy = y + dir[i][1];
}
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if (grid[xx][yy] == '#') continue;
q.push({xx, yy, depth+1});
}
}
if (flag) cout << depth << endl;
else cout << -1 << endl;
return 0;
}
我想问下各位做出来的大佬,这个跳跃限制如何加入进去? 