本人在学习C语言,对c++一窍不通,希望帮忙
以下是代码(实现bfs迷宫自动寻路,希望改动尽量少)
#include <bits/stdc++.h>
using namespace std;
struct que
{
int x, y, s, f;
} node[250];
int main()
{
int fill[50][50], book[50][50];
memset(book, 0, sizeof(book));
int m, n; // m->x n->y
int start_x, start_y, finish_x, finish_y;
int head = 1, tail = 1;
int tx, ty; //下一步的位置坐标
bool flag = false; //用于结束双层循环
//初始化迷宫地图
cin >> m >> n;
for (int y = 0; y < n; y++)
for (int x = 0; x < m; x++)
cin >> fill[y][x];
cin >> start_x >> start_y >> finish_x >> finish_y;
//初始化迷宫入口
book[start_y][start_x] = 1;
node[tail].x = start_x;
node[tail].y = start_y;
node[tail].f = 0;
node[tail].s = 0;
tail++;
//寻路
while (head < tail)
{
for (int ctrl = 0; ctrl < 4; ctrl++) //控制下一步行走方向
{
switch (ctrl)
{
case 0: //向右走
tx = node[head].x + 1;
ty = node[head].y;
break;
case 1: //向下走
tx = node[head].x;
ty = node[head].y + 1;
break;
case 2: //向左走
tx = node[head].x - 1;
ty = node[head].y;
break;
case 3: //向上走
tx = node[head].x;
ty = node[head].y - 1;
break;
}
if (tx < 0 || tx > m - 1 || ty < 0 || ty > n - 1)
continue; //如果撞了围墙就返回
if (fill[ty][tx] == 0 && book[ty][tx] == 0)
{
node[tail].s = node[head].s + 1;
node[tail].x = tx;
node[tail].y = ty;
node[tail].f = head;
book[ty][tx] = 1;
tail++;
} //如果下一步没有撞墙,并且没有走过这个地方
if (ty == finish_x && ty == finish_y)
{
flag = true;
break; //如果走到终点,停止行走
}
}
if (flag)
break; //flag的妙用[手动滑稽]
head++;
}
cout << node[tail - 1].s << endl; //打印出从起点走了多少步到终点
//倒序输出所经过的位置的坐标
cout << finish_x << finish_y << endl;
int temp = node[tail - 1].f;
while (temp != 0)
{
cout << node[temp].x << node[temp].y << endl;
fill[node[temp].y][node[temp].x] = 2;
temp = node[temp].f;
}
fill[finish_y][finish_x] = 2;
for (int y = 0; y < n; y++)
{
for (int x = 0; x < m; x++)
cout << fill[y][x] << " ";
cout << endl;
}
system("pause");
return 0;
}