下午好🌅🌅🌅
本答案参考ChatGPT-3.5
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int dfs(vector<vector<int>>& maze, int ch, int cw, int dh, int dw, int dest) {
if (ch == dest || abs(dh - dw) <= 2 || abs(ch - cw) <= 2 || abs(dh - ch) <= 2) return 0;
if (maze[ch][cw] != '#') return 0; // 白色不能走
for (int i = 1; i <= maze.size(); ++i) {
vector<vector<int>> temp(maze[i].size(), vector<int>(4));
for (int j = 0; j <= maze[i].size(); ++j) {
temp[j][0] = maze[i][j];
temp[j][1] = maze[i][j+1];
temp[j][2] = maze[i][j+2];
temp[j][3] = maze[i][j+3];
}
int cost = dfs(temp, ch + 1, cw, dh, dw, dest);
if (cost > 0)
return cost;
}
return -1; // 最少需要4次魔法
}
private:
vector<vector<int>> maze;
};
int main() {
Solution solution;
vector<vector<int>> maze = {{1, 1, 0, 0, 0},
{1, 0, 1, 0, 0},
{0, 1, 0, 1, 1},
{0, 0, 1, 1, 0},
{0, 0, 0, 1, 1}};
int ch = 1, cw = 1;
int dh = 0, dw = 0;
int dest = 4;
cout << "Solution: " << solution.dfs(maze, ch, cw, dh, dw, dest) << endl;
return 0;
}
在这个代码中,我们首先定义了一个名为Solution的类,并实现了dfs函数来解决这个问题。该函数接受迷宫的二维数组和当前位置作为参数,以及目标位置和魔法等级。dfs函数的主要逻辑是递归地搜索所有可能的路径,每次循环更新当前状态,并递归地计算新的路径。
我们还定义了起始和结束点坐标,以及魔法等级的目标值。最后,我们在主函数中创建了一个迷宫对象,并调用了dfs函数来获取最少使用的魔法次数。