版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011718609/article/details/56678721
题目:迷宫矩阵(n*m)的每一个元素可以是0或1,1表示可走,0表示走不通,迷宫的入口为(0,0),出口为(0,m-1)。青蛙的体力值为P,向右走消耗1个体力值,向下走不消耗体力值,向上走消耗3个体力值。如果体力消耗最少的路径所消耗的体力值大于P,则输出“Can not escape”,否则,输出青蛙走出迷宫的体力消耗最少的路径和消耗的体力值。
输入:第一行:n m P;
第n-1行:迷宫矩阵
例:输入:
4 4 10
1 0 1 1
1 1 0 1
1 1 1 1
1 1 1 1
输出:0,0->1,0->2,0->2,1->2,2->2,3->1,3->0,3
9
代码
采用深度优先搜索,递归的向右、下、上三个方向搜索
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int flag=0; //全局变量,判断是否有路可以走
/**********************************
n,m:当前访问的位置
path:记录路径
minpath:记录最小路径
power:当前剩余能量
minpower:最大剩余能量(消耗最少能量)
mazing:迷宫
visited:记录节点是否被访问过
**********************************/
void dfs(int n, int m, int x, int y,vector<int>& path,vector<int>& minpath,int power,int &minpower,
vector<vector<int>>& mazing, vector<vector<int>>& visited)
{
if (power < 0)
return;
if (x == 0 && y == m - 1)
{
if (power > minpower)
{
path.push_back(x);
path.push_back(y);
flag = 1; //找到一次就让标记置1,说明有通路
minpower = power;
minpath = path;
path.pop_back();
path.pop_back();
}
}
else{
path.push_back(x);
path.push_back(y);
visited[x][y] = 1;
if (x + 1 < n && visited[x + 1][y] == 0 && mazing[x+1][y] == 1)
dfs(n, m, x + 1, y, path, minpath, power, minpower, mazing, visited);
if (x - 1 >= 0 && visited[x - 1][y] == 0 && mazing[x-1][y] == 1)
dfs(n, m, x - 1, y, path, minpath, power-3, minpower, mazing, visited);
if (y + 1 < m && visited[x][y+1] == 0 && mazing[x][y+1] == 1)
dfs(n, m, x, y+1, path, minpath, power-1, minpower, mazing, visited);
path.pop_back();
path.pop_back();
visited[x][y] = 0;
}
}
int main(void)
{
int n, m, P;
int minP = 0;
cin >> n >> m >> P;
vector<vector<int>> mazing(n, vector<int>(m, 0));
vector<vector<int>> visited(n, vector<int>(m, 0)); //动态二维数组定义!!
vector<int> path;
vector<int> minpath;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> mazing[i][j];
}
}
dfs(n, m,0,0,path,minpath,P,minP,mazing,visited); //核心程序,递归
if (flag)
{
for (int i = 0; i < minpath.size(); i += 2)
cout << minpath[i] << "," << minpath[i + 1] << "->";
cout << endl;
cout << P - minP;
}
else
cout << "Can not escape";
system("pause");
return 0;
}