Why does my Flood Fill sorting not work?

I have some code here:

local cells = {}
local rooms = {}
local visited = {}
local directions = {
	Vector2.new(1,0),
	Vector2.new(0,1),
	Vector2.new(-1,0),
	Vector2.new(0,-1),
}
function FloodFill(x,y,room)
	if x < 1 or y < 1 or x > size or y > size or cells[x][y]["Type"] ~= "Empty" then
		return
	end
	visited[x][y] = true
	table.insert(room,{x,y})
	for _,dir in pairs(directions) do
		local dx,dy = x+dir.X,y+dir.Y
		table.insert(room,{dx,dy})
		FloodFill(dx,dy,room)
	end
	return room
end

function SortIntoRooms()
	for x=1,size do
		visited[x] = {}
		for y=1,size do
			visited[x][y] = false
		end
	end
	for x=1,size do
		for y=1,size do
			if cells[x][y]["Type"] == "Empty" and visited[x][y] == false then
				local room = FloodFill(x,y,{})
				table.insert(rooms,room)
			end
		end
		task.wait()
	end
end
SortIntoRooms()

But it just errors like this:
image

Sorry if this sounds stupid, but I’m doing this while extremely tired!

I’m just trying to sort all my cells into rooms
there are two types; Empty and Wall

(Yes it should work, I have a basic map that shows up when it reaches the part where the map turns into a 3D version in the workspace)

ignore the requested module part, that’s erroring because the module timed out

1 Like

Which line is line 107?
What’s the error associated with the traceback?

I showed the error… theres literally no info lol.

Ok, well running the code you sent, and setting size to 5, i got the following error:


But i don’t know if that’s just because there’s other code you haven’t included in the post.

1 Like

There’s around 200 lines I didnt add.

1 Like

So I rewrote it into three functions now, and it worked!

function FloodFill(x,y,room)
	if cells[x][y]["Type"] == "Empty" and x > 0 and y > 0 and x <= size and y <= size and not visited[x][y] then
		visited[x][y] = true
		for _,dir in pairs(directions) do
			local dx,dy = dir.X,dir.Y
			local nx,ny = x+dx,y+dy
			if cells[nx] and cells[nx][ny] then
				table.insert(room,{nx,ny})
				FloodFill(nx,ny,room)
			end
		end
	end
end

function DetectRoom(x,y)
	if cells[x][y]["Type"] == "Empty" and x > 0 and y > 0 and x <= size and y <= size and not visited[x][y] then
		local room = {}
		FloodFill(x,y,room)
		return room
	else
		return
	end
end

function SortIntoRooms()
	for x=1,size do
		visited[x] = {}
		for y=1,size do
			visited[x][y] = false
		end
	end
	for x=1,size do
		for y=1,size do
			if cells[x][y]["Type"] == "Empty" and not visited[x][y] then
				local room = DetectRoom(x,y)
				if room then
					table.insert(rooms,room)
				end
				task.wait()
			end
		end
		task.wait()
	end
end

1 Like