网易笔试题——推箱子
题目:大家一定玩过“推箱子”这个经典的游戏。具体规则就是在一个N*M的地图上,有1个玩家、1个箱子、1个目的地以及若干障碍,其余是空地。玩家可以往上下左右4个方向移动,但是不能移动出地图或者移动到障碍里去。如果往这个方向移动推到了箱子,箱子也会按这个方向移动一格,当然,箱子也不能被推出地图或推到障碍里。当箱子被推到目的地以后,游戏目标达成。现在告诉你游戏开始是初始的地图布局,请你求出玩家最少需要移动多少步才能够将游戏目标达成。
输入描述:
每个测试输入包含1个测试用例
第一行输入两个数字N,M表示地图的大小。其中0<N,M<=80<N,M<=8。
接下来有N行,每行包含M个字符表示该行地图。其中 . 表示空地、X表示玩家、*表示箱子、#表示障碍、@表示目的地。
每个地图必定包含1个玩家、1个箱子、1个目的地。
输出描述:
输出一个数字表示玩家最少需要移动多少步才能将游戏目标达成。当无论如何达成不了的时候,输出-1。
输入例子:
4 4
….
..*@
….
.X..
6 6
…#..
……
#*##..
..##.#
..X…
.@#…
输出例子:
3
11
以人的角度来广度优先遍历图,st[10][10][10][10]用来存储人的位置和箱子的位置,map存储原始数据,从人的位置开始往四个方向遍历,依次判断是否符合条件,并需要更新路径长度。
// Study.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> #include <string> #include <algorithm> #include <sstream> #define INT_MAX 2147483647 // maximum (signed) int value #define INT_MIN (-2147483647 - 1) // minimum (signed) int value using namespace std; int st[10][10][10][10]; vector<vector<char>> map; int tx, ty; int minStep = INT_MAX; bool valid(int x, int y) { if (map.size() < 1) return 0; int rows = map.size(); int cols = map[0].size(); if (x < 0 || x >= rows || y < 0 || y >= cols || map[x][y] == '#') return 0; return 1; } int main() { //输入地图,并初始化 int N, M; cin >> N >> M; char tmp; int x, y, bx, by; map = vector<vector<char>>(N, vector<char>(M, '.')); vector<vector<int>> next = { {0,1},{-1,0},{0,-1},{1,0} }; queue<vector<int>> state; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> tmp; if (tmp != '.') { map[i][j] = tmp; if (tmp == 'X') { x = i; y = j; } else if (tmp == '*') { bx = i; by = j; } else if (tmp == '@') { tx = i; ty = j; } } } } //图的广度遍历BFS state.push({ x,y,bx,by }); st[x][y][bx][by] = 1; // vector<vector<int>> path; while (!state.empty()) { vector<int> current = state.front(); state.pop(); x = current[0]; y = current[1]; bx = current[2]; by = current[3]; for (int i = 0; i < next.size(); i++) { int nx = x + next[i][0], ny = y + next[i][1]; int nnx = nx + next[i][0], nny = ny + next[i][1]; if (valid(nx, ny) && (nx != bx || ny != by) && st[nx][ny][bx][by] == 0) { st[nx][ny][bx][by] = st[x][y][bx][by] + 1; state.push({ nx,ny,bx,by }); } else if ( nx == bx && ny == by && valid(nnx, nny) && st[nx][ny][nnx][nny] == 0) { st[nx][ny][nnx][nny] = st[x][y][bx][by] + 1; if (nnx == tx && nny == ty) { cout << st[nx][ny][nnx][nny] - 1 << endl; std::system("pause"); return 0; } else state.push({ nx,ny,nnx,nny }); } } } cout << -1 << endl; std::system("pause"); return 0; }