Wednesday, May 3, 2017

unity - How to make Flood fill algorithm return different Lists of separate groups in the grid?


So i have this flood fill method :


 public int groupedCells(int y, int x, int value)
{
//base state
if (!gSetup.isValidLocation(y, x) ||
gSetup.getCell(y, x).value != value ||
gSetup.getCell(y, x).cMAtch.isInMatchPool)
{
return 0;

}

// keep track of matched cells
gSetup.getCell(y, x).cMAtch.isInMatchPool = true;

// collect
int up = groupedCells(y + 1, x, value); // up
int left = groupedCells(y, x - 1, value); // left
int right = groupedCells(y, x + 1, value); // right
int down = groupedCells(y - 1, x, value); // down


// sum
int total = up + left + right + down + 1;

return total;
}

basically i have this grid :


enter image description here


and currently if i click on a yellow triangle, the method above will tell me how many of them are next to each other.



What i want is a solution that will run all over the grid, and check if a group has :




  • less than 3-triangles then do (A)




  • if it has 3-triangles then do (B)




  • if it has 4-triangles then do (C)





etc ...


Am not sure about this, but i thought the best way is to have a list for every group, and then check those conditions over the lists.


I tried it here but the list keep re-initializing itself, so it always either have 0 cells or 1 :


  public List listedCells(int y, int x, int value)
{
List cList = new List();
//base state
if (!gSetup.isValidLocation(y, x) ||

gSetup.getCell(y, x).value != value ||
gSetup.getCell(y, x).cMAtch.isInMatchPool)
{
return cList;
}

// keep track of matched cells
gSetup.getCell(y, x).cMAtch.isInMatchPool = true;
cList.Add(gSetup.getCell(y, x));
// collect

List up = listedCells(y + 1, x, value); // up
List left = listedCells(y, x - 1, value); // left
List right = listedCells(y, x + 1, value); // right
List down = listedCells(y - 1, x, value); // down


return cList;
}

The result of that method when its called here :



for (int y = 0; y < gSetup.cell2DArray.GetLength(0); y++)
{
for (int x = 0; x < gSetup.cell2DArray.GetLength(1); x++)
{

print(listedCells(y, x, 1).Count);
}
}

is printing "1" three times and "0" 22 times.



Thank you



Answer



as written, your listedCells function needs to take cList as a parameter so you don't create a new list for every recursive call.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...