来源:https://blog.csdn.net/gladyoucame/article/details/8803904#commentBox
题目:
有一个6*6的棋盘,每个棋盘上都有一个数值,现在又一个起始位置和终止位置,请找出一个从起始位置到终止位置代价最小的路径:
1、只能沿上下左右四个方向移动
2、总代价是每走一步的代价之和
3、每步(从a,b到c,d)的代价是c,d上的值与其在a,b上的状态的乘积
4、初始状态为1,每走一步,状态按如下公式变化:(走这步的代价%4)+1。
个人理解:本质上是一个带权树的最短路径搜索问题,直观反应采用BFS搜索。
自己先暂且记录一下。
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
int x, y, sum, statu;
};
int ans;
int map[6][6];
int opt[6][6][4]; //记录最优解,剪枝条件。4中状态都要记录
Node start;
int ex, ey;
int cnt = 0;
int dir[4][2] = { { 0, 1 },{ 1, 0 },{ 0, -1 },{ -1, 0 } };
queue<Node> q;
void bfs(Node n)
{
q.push(n);
int tempx, tempy, cost;
while (!q.empty())
{
cnt++;
Node tn = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
tempx = tn.x + dir[i][0];
tempy = tn.y + dir[i][1];
if (tempx >= 0 && tempx < 6 && tempy >= 0 && tempy < 6)
{
cost = tn.statu * map[tempx][tempy];
//如果这一步比以前的某一步代价还大 或者 比到终点的代价还大
if (tn.sum + cost < opt[tempx][tempy][cost % 4] && tn.sum + cost < opt[ex][ey][cost % 4])
{
opt[tempx][tempy][cost % 4] = tn.sum + cost;
Node temp;
temp.x = tempx;
temp.y = tempy;
temp.sum = tn.sum + cost;
temp.statu = cost % 4 + 1;
q.push(temp);
}
}
}
}
}
int main()
{
while (1)
{
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
{
cin >> map[i][j];
for (int k = 0; k < 4; k++)
opt[i][j][k] = 100000;
}
start.sum = 0;
start.statu = 1;
ans = 100000;
cin >> start.x >> start.y >> ex >> ey;
if (start.x == ex && start.y == ey) {
cout << 0 << endl;
return 0;
}
bfs(start);
for (int i = 0; i < 4; i++)
{
if (ans > opt[ex][ey][i])
ans = opt[ex][ey][i];
}
//cout << cnt << endl;
cout << ans << endl;
}
return 0;
}