以下为移植代码(在ARDUINO中无法运行)
char a;
int b;
char c;
typedef struct node
{
int x,y;
int pre;
}strnode;
int ans,d[4][2] = { {-1,0},{0,-1},{1,0},{0,1} },m[5][5],v[5][5];
strnode que[200];
void bfs();
void output(int ans);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
int i = 0, k, j = 0;
for (i = 0; i <5; i++)
{
for (j = 0; j < 5; j++) {
c=Serial.read();
m[i][j]=Serial.parseInt();
}
}
bfs();
output(ans);
}
void loop() {
// put your main code here, to run repeatedly:
}
void bfs()
{
memset(v, 0, sizeof(v));
int head = 0, tail = 0, i = 0;
que[tail].x = 0;
que[tail].y = 0;
que[tail++].pre = -1;
v[0][0] = 1;
while (head < tail)
{
strnode temp = que[head++];
if (temp.x == 4 && temp.y == 4)
{
ans = head - 1;
return;
}
for (i = 0; i < 4; i++)
{
int dx = temp.x + d[i][0];
int dy = temp.y + d[i][1];
if (!v[dx][dy] && !m[dx][dy]&&dx>=0&&dy>=0&&dx<5&&dy<5)
{
que[tail].x = dx;
que[tail].y = dy;
que[tail++].pre = head - 1;
v[dx][dy] = 1;
}
}
}
}
void output(int ans)
{
if (que[ans].pre != -1)
{
output(que[ans].pre);
}
Serial.print(que[ans].x);
Serial.println(que[ans].y);
return;
}
运行结果就是不停输出-1
用广搜走解决迷宫问题,然后输出路线
在串口中用0,1以二维数组形式在串口中输入迷宫,然后在串口中输出结果