有一个推箱子的游戏, 一开始的情况如下图:
上图中, '.' 表示可到达的位置, '#' 表示不可到达的位置,其中 S 表示你起始的位置, 0表示初始箱子的位置, E表示预期箱子的位置,你可以走到箱子的上下左右任意一侧, 将箱子向另一侧推动。如下图将箱子向右推动一格;
..S0.. -> ...S0.
注意不能将箱子推动到'#'上, 也不能将箱子推出边界;
现在, 给你游戏的初始样子, 你需要输出最少几步能够完成游戏, 如果不能完成, 则输出-1。
..S0.. -> ...S0.
注意不能将箱子推动到'#'上, 也不能将箱子推出边界;
现在, 给你游戏的初始样子, 你需要输出最少几步能够完成游戏, 如果不能完成, 则输出-1。
第一行为2个数字,n, m, 表示游戏盘面大小有n 行m 列(5< n, m < 50);
后面为n行字符串,每行字符串有m字符, 表示游戏盘面;
一个数字,表示最少几步能完成游戏,如果不能,输出-1;
3 6 .S#..E .#.0.. ......
11
//编程题1
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <memory.h>
#include <queue>
#include <functional>
using namespace std;
int rows, cols;
vector<string> mat;
bool visited[50][50][50][50];
struct Step
{
int manx, many;
int boxx, boxy;
int times;
bool checkman()
{
return manx >= 0 && manx < cols && many >= 0 && many < rows && mat[many][manx] == '.';
}
bool checkbox()
{
return boxx >= 0 && boxx < cols && boxy >= 0 && boxy < rows && mat[boxy][boxx] == '.';
}
bool checkvisit()
{
if (visited[manx][many][boxx][boxy])
return true;
visited[manx][many][boxx][boxy] = true;
return false;
}
};
int main(int argc, char** argv) {
cin >> rows >> cols;
mat.resize(rows);
int expectx, expecty;
Step InitStep;
for (size_t i = 0; i < rows; i++)
{
cin >> mat[i];
for (size_t j = 0; j < cols; j++)
{
if (mat[i][j] == 'S') {
InitStep.manx = j;
InitStep.many = i;
mat[i][j] = '.';
}
if (mat[i][j] == '0') {
InitStep.boxx = j;
InitStep.boxy = i;
mat[i][j] = '.';
}
if (mat[i][j] == 'E') {
expectx = j;
expecty = i;
mat[i][j] = '.';
}
}
}
InitStep.times = 0;
int dirs[4][2] = {
{ -1,0 },
{ 0,1 },
{ 1,0 },
{ 0,-1 }
};
memset(visited, 0, 50 * 50 * 50 * 50);
queue<Step> q;
q.push(InitStep);
int result = -1;
while (result == -1 && !q.empty())
{
Step front = q.front();
q.pop();
for (size_t dir = 0; dir < 4; dir++)
{
//方向 左下右上
Step nextStep = front;
nextStep.times++;
nextStep.manx += dirs[dir][0];
nextStep.many += dirs[dir][1];
if (!nextStep.checkman())
continue;
if (nextStep.manx == nextStep.boxx &&
nextStep.many == nextStep.boxy) {
nextStep.boxx += dirs[dir][0];
nextStep.boxy += dirs[dir][1];
if (!nextStep.checkbox())
continue;
}
if (nextStep.checkvisit())
continue;
if (nextStep.boxx == expectx &&
nextStep.boxy == expecty)
{
//cout << "找到"<<nextStep.times << endl;
result = nextStep.times;
break;
}
q.push(nextStep);
}
}
cout << result << endl;
return 0;
}
更多牛客网题解代码从https://github.com/ReyzalX/nowcoder获取