I developed a method for analyzing traffic in a game where roads are already laid out in a grid. It starts at an initial road and continues to examine adjacent roads until it covers 10 road segments. When the method reaches a crossroad, it continues to explore one direction within the current block while simultaneously initiating searches in the other directions at that crossroad. This approach divides the entire road network into blocks, each containing 10 segments, to assess the traffic on each. The method works, but the process of dividing the roads into blocks is resource-intensive. I'm looking for suggestions to optimize this or for alternative approaches that can achieve the same result with better performance.
Here is my code. It works but it needs optimization.
void CheckTraffic(Road road)
{
closed.Add(road);
block.Add(road);
List<Road> neighbours = road.Neighbours(closed);
if(neighbours.Count > 0)
{
int index = -1;
if (block.Count == 1)
{
index = 0;
}
else if (block.Count == roadCountInBlock)
{
WriteTraffic(block);
block = new List<Road>();
}
else
{
int r = road.startSlot.row - block[block.Count - 2].startSlot.row;
int c = road.startSlot.column - block[block.Count - 2].startSlot.column;
if( Mathf.Abs(r) + Mathf.Abs(c) == 1)
{
r += road.startSlot.row;
c += road.startSlot.column;
index = neighbours.FindIndex(item => item.startSlot.row == r && item.startSlot.column == c);
}
else
{
WriteTraffic(block);
block = new List<Road>();
}
}
if (index == -1)
{
index = 0;
}
CheckTraffic(neighbours[index]);
for(int i=0; i<neighbours.Count; i++)
{
if (!closed.Contains(neighbours[i])) CheckTraffic(neighbours[i]);
}
}
else
{
WriteTraffic(block);
block = new List<Road>();
}
}