Breadth-First Search not working correctly

Hi!

  1. What do you want to achieve? I want to make a pathfinding system for soldiers in a WW1 grand strategy game.

  2. What is the issue? I tried making it use BFS and it just randomly picks places for the final path.

  3. What solutions have you tried so far? I tried comparing my code to another BFS algorithm.

Here is my code (Please note that this is currently for testing pathfinding, this only shows the best path, in theory. That’s why there is the wait(4) before running the function.):

local function ShowPathToGoal(explored, goal, s)
	local path = {}
	local currentNode = goal
	while currentNode and currentNode.Name ~= s.Name do
		local num = tonumber(string.split(currentNode.Name,"e")[2])
		
		print(num)
		
		print(currentNode)
		table.insert(path, 1, currentNode)
		currentNode = explored[num]
		wait(0.1)
	end
	print(currentNode)
	print(explored)
	print(path)
	
	for _,node in pairs(path) do
		--if node ~= goal then
			node.BrickColor = BrickColor.new("Shamrock")
		--end
	end
end

function BFS(s,f)
	local queue = {s}
	local explored = {}
	local goalReached = false
	
	while #queue ~= 0 do
		local slot = queue[1]
		
		if slot == f then
			goalReached = true
			break
		end
		
		if slot ~= s then
			slot.BrickColor = BrickColor.new("White")
		end
		
		table.remove(queue, 1)
		
		local neighbors = workspace:GetPartsInPart(slot)
		if #neighbors > 0 then
			for i,v in pairs(neighbors) do
				if v:FindFirstChild("Obstacle") then continue end
				if not table.find(explored,v) and not table.find(queue, v) then
					table.insert(explored,slot)
					table.insert(queue,v)
				end
			end
		else
			break
		end
	end
	--print(explored)
	if goalReached then
		ShowPathToGoal(explored, f, s)
	end
end

wait(4)

BFS(workspace.France["Alsace-Lorraine"].Tile33,workspace["Polish Republic"].Koenigsburg.Tile58)

Here is the picture of what it shows (White is the explored tiles, and the green is what it says is the best path. Blue tile is starting tile, and one in the east is the ending tile.):

Thanks!