Labyrinth/src/bfs.c

87 lines
2.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include "../include/labyrinth.h"
#include "../include/bfs.h"
#include "../include/queue.h"
#include "../include/coor.h"
void bfs(Labyrinth* labyrinth){
int i, j;
int arr[4] = {0, 1, 2, 3}, tmp, tp;
coor* cor = (coor*)malloc(sizeof(coor));
coor* test;
cor->x = labyrinth->start.x;
cor->y = labyrinth->start.y;
queue(q);
queuePush(q, cor);
while(!queueIsEmpty(q)){
test = (coor*)q->front->element;
i = test->x;
j = test->y;
queuePop(q);
if(i==labyrinth->end.x && j==labyrinth->end.y){
queueFree(q);
find_path(labyrinth);
return;
}
if(i!=labyrinth->start.x || j!=labyrinth->start.y)
labyrinth->at[i][j].color = GREEN;
printLab(labyrinth);
labyrinth->at[i][j].visited = true;
for(int h=3; h>0; h--){
tmp = rand()%h;
tp = arr[h];
arr[h] = arr[tmp];
arr[tmp] = tp;
}
// goes in the direction if possible
for(int h=0; h<4; h++){
coor* cor2 = (coor*)malloc(sizeof(coor));
if(arr[h]==0){
if(i>0 && labyrinth->at[i-1][j].south && !labyrinth->at[i-1][j].visited){
if(i-1!=labyrinth->end.x && j!=labyrinth->end.y)
labyrinth->at[i-1][j].color = ORANGE;
labyrinth->at[i-1][j].direction = UP;
cor2->x = i-1;
cor2->y = j;
queuePush(q, cor2);
}
}else if(arr[h]==1){
if(j<labyrinth->y_size-1 && labyrinth->at[i][j].east && !labyrinth->at[i][j+1].visited){
if(i!=labyrinth->end.x && j+1!=labyrinth->end.y)
labyrinth->at[i][j+1].color = ORANGE;
labyrinth->at[i][j+1].direction = RIGHT;
cor2->x = i;
cor2->y = j+1;
queuePush(q, cor2);
}
}else if(arr[h]==2){
if(i<labyrinth->y_size-1 && labyrinth->at[i][j].south && !labyrinth->at[i+1][j].visited){
if(i+1!=labyrinth->end.x && j!=labyrinth->end.y)
labyrinth->at[i+1][j].color = ORANGE;
labyrinth->at[i+1][j].direction = DOWN;
cor2->x = i+1;
cor2->y = j;
queuePush(q, cor2);
}
}else if(arr[h]==3){
if(j>0 && labyrinth->at[i][j-1].east && !labyrinth->at[i][j-1].visited){
if(i!=labyrinth->end.x && j-1!=labyrinth->end.y)
labyrinth->at[i][j-1].color = ORANGE;
labyrinth->at[i][j-1].direction = LEFT;
cor2->x = i;
cor2->y = j-1;
queuePush(q, cor2);
}
}
}
}
}