Hi! I have an interesting problem.
I have drawn in a HTML canvas a series of hexagons (ignore the dots)
For each hexagon I have it's x and y coordinates of their center, that's how I identify them.
I store the hexagons in an array called hexagons where I store Hexagons
function Hexagon()
{
this.shape
this.x
this.y
}
I have a function that returns an object with all the adjacent hexagons of a given hexagon
function get_adjacent_hexagons(hexagon)
{
var x = hexagon.x
var y = hexagon.y
var adjacents = []
for(var i=0; i<editor_hexagons.length; i++)
{
if(editor_hexagons[i].x === x && editor_hexagons[i].y == y - (2*s))
{
adjacents.push(editor_hexagons[i])
}
if(editor_hexagons[i].x === x && editor_hexagons[i].y == y + (2*s))
{
adjacents.push(editor_hexagons[i])
}
if(editor_hexagons[i].x === x - (s*1.5) && editor_hexagons[i].y == y - s)
{
adjacents.push(editor_hexagons[i])
}
if(editor_hexagons[i].x === x - (s*1.5) && editor_hexagons[i].y == y + s)
{
adjacents.push(editor_hexagons[i])
}
if(editor_hexagons[i].x === x + (s*1.5) && editor_hexagons[i].y == y - s)
{
adjacents.push(editor_hexagons[i])
}
if(editor_hexagons[i].x === x + (s*1.5) && editor_hexagons[i].y == y + s)
{
adjacents.push(editor_hexagons[i])
}
}
return adjacents
}
Given this information, is it possible to make an algorithm to check if all the hexagons are connected
That is if there is no hexagon or group of hexagons on their own?
For example in the picture provided they are all connected.
----- EDIT -----
This seems to be working
function check_connection()
{
visited = []
visit_hexagon(hexagons[0])
}
function visit_hexagon(hexagon)
{
var not_visited = true
for(var i=0; i<visited.length; i++)
{
if(visited[i] === hexagon)
{
not_visited = false
break
}
}
if(not_visited)
{
visited.push(hexagon)
var adjacents = get_adjacent_hexagons(hexagon)
for(var i=0; i<adjacents.length; i++)
{
visit_hexagon(adjacents[i])
}
}
}