# [SOLVED] Path find gets stuck in dead ends

I am trying to make my own path find using the A* algorithm. It works fine, but it gets stuck in dead ends.

For example:

When I find the path, it works fine:

But when I do something as simple as this:

It fails!

Code:

``````local start = workspace.Nodes.start
local endd = workspace.Nodes.endd

local length = 2

local current = start

local closedList = {}

local function findClosest(parts)
local costs = {}
local partss = {}
for _,v in pairs(parts) do
local huer = (v.Position-endd.Position).Magnitude
local mag = (v.Position-current.Position).Magnitude
partss[huer+mag]=v
table.insert(costs,huer+mag)
end
if (#costs < 1) then return false end
return partss[math.min(unpack(costs))]
end

local function getNeighbours(p)
local right = p.CFrame.RightVector
local left = -right
local front = p.CFrame.LookVector
local back = -front
local R = workspace:FindPartOnRayWithWhitelist(Ray.new(p.Position,right*length),workspace.Nodes:GetChildren())
local L = workspace:FindPartOnRayWithWhitelist(Ray.new(p.Position,left*length),workspace.Nodes:GetChildren())
local F = workspace:FindPartOnRayWithWhitelist(Ray.new(p.Position,front*length),workspace.Nodes:GetChildren())
local B = workspace:FindPartOnRayWithWhitelist(Ray.new(p.Position,back*length),workspace.Nodes:GetChildren())
local neigh = {}
if (R) and (not table.find(closedList,R)) then
neigh[#neigh+1]=R
end
if (L) and (not table.find(closedList,L)) then
neigh[#neigh+1]=L
end
if (F) and (not table.find(closedList,F)) then
neigh[#neigh+1]=F
end
if (B) and (not table.find(closedList,B)) then
neigh[#neigh+1]=B
end
return neigh
end

local path = {}

while true do
local nearest,ind = findClosest(getNeighbours(current))
if (not nearest) then
print("FAILED")
break
end
local ray = Ray.new(current.Position,(current.Position-nearest.Position).Unit*(current.Position-nearest.Position).Magnitude)
local part = workspace:FindPartOnRay(ray,workspace.Nodes)
if (not part) then
table.insert(closedList,current)
current = nearest
table.insert(path,nearest)
if (nearest==endd) then
print("REACH")
break
end
else
local prev = closedList[#closedList-3]
local ind = table.find(closedList,prev)
table.remove(closedList,ind)
current = prev
end
end

for i = #path,1,-1 do
local v = path[i]
v.BrickColor = BrickColor.Black()
wait()
end
``````

How can I fix this?
Thanks!

(A better implementation of this algorithm will be greatly appreciated.)