I have a grid of connected paths as shown below:
The grid is a 2D array created as follows:
for(var x = 0; x < 10; x++){
hz[x] = new Array(10);
for(var y = 0; y < 10; y++){
hz[x][y] = new block(0, 0, 0, 0, 0);
}
}
Each element of the array contains an object of type block
as follows:
function block(top, bottom, left, right, visited){
this.top = top;
this.bottom = bottom;
this.left = left;
this.right = right;
this.visited = visited;
}
I have implemented a breadth-first-search on my grid in order to define the connected components. I need it to be completely connected. This is my code for the BFS:
function search(){
var count = 0;
var graph = hz;
for(var x=0; x < 9; x++){
for(var y=0; y < 9; y++){
if(!graph[x][y].visited){ //if block not yet visited
count++;
q = new Queue();
q.enqueue(graph[x][y]);
graph[x][y].visited = 1;
while(q.size() > 0){
var w = q.dequeue();
var ends = numberOfEnds(w);
var a = w.x;
var b = w.y;
for(var t=0; t < ends; t++){
if(w.left){
if(graph[a][b-1].right){
if(!graph[a][b-1].visited){
graph[a][b].left = 0;
graph[a][b-1].visited = 1;
q.enqueue(graph[a][b-1]);
}
}
}
else if(w.right){
if(graph[a][b+1].left){
if(!graph[a][b+1].visited){
graph[a][b].right = 0;
graph[a][b+1].visited = 1;
q.enqueue(graph[a][b+1]);
}
}
}
else if (w.top){
if(graph[a-1][b].bottom){
if(!graph[a-1][b].visited){
graph[a][b].top = 0;
graph[a-1][b].visited = 1;
q.enqueue(graph[a-1][b]);
}
}
}
else if (w.bottom){
if(graph[a+1][b].top){
if(!graph[a+1][b].visited){
graph[a][b].bottom = 0;
graph[a+1][b].visited = 1;
q.enqueue(graph[a+1][b]);
}
}
}
} //end for every neighbour of block
} //end while
} //end if visited
} //end for y
} //end for x
console.log("Count: " + count);
}
The problem is that when I run the algorithm, the result of count
is very high, like in the 50s when it should be 1 or 2 at the most.
What am I doing wrong?