题目
题目真的长,还有很多细节。
#include <iostream>
#include <string>
using namespace std;
struct Coordinate{
int row;
int col;
};
const int MAX_SIZE = 20;
Coordinate start, goal;
Coordinate dir[4] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}}; // 四个方向,按照小键盘 2 4 6 8 的顺序排列
int matrix[MAX_SIZE][MAX_SIZE];//迷宫
int width, height, cnt_mov;
bool exist_flag;//标记是否存在到达终点的路线
void dfs(int row, int col, int steps)
{
if (steps == 11)
return;
for (int i = 0; i < 4; i++){//遍历四个方向
int dis = 0;
int tmp_row = row;//临时行和列
int tmp_col = col;//用于回溯
while (1){//一直朝着同一个方向走,直到碰到障碍或者到达终点。
tmp_row += dir[i].row;
tmp_col += dir[i].col;
dis++;//标记每次直线走过的方格数
if (tmp_row < 0 || tmp_row >= height || tmp_col < 0 || tmp_col >= width)
break;
if (matrix[tmp_row][tmp_col] == 0)
continue;
else if (matrix[tmp_row][tmp_col] == 3){
if (cnt_mov > steps )//记录最短步数
cnt_mov = steps;
exist_flag = true;//标记
return;
}
else if (matrix[tmp_row][tmp_col] == 1){
if (dis > 1){//dis > 1 说明障碍距离起点之间至少有一个空格
matrix[tmp_row][tmp_col] = 0;
dfs(tmp_row - dir[i].row, tmp_col - dir[i].col, steps + 1);
matrix[tmp_row][tmp_col] = 1;
}
break;
}
}
}
}
int main()
{
while (cin >> width >> height && !(width == 0 && height == 0)){
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
cin >> matrix[i][j];
if (matrix[i][j] == 2){
start.row = i;
start.col = j;
}
else if (matrix[i][j] == 3){
goal.row = i;
goal.col = j;
}
}
}
cnt_mov = 2333;//初始步数大于存在的最短步数即可
exist_flag = false;//初始标记
dfs(start.row, start.col, 1);
if (exist_flag){
cout << cnt_mov << endl;
}
else {
cout << "-1" << endl;
}
}
return 0;
}