Guest User

Untitled

a guest
Oct 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. /// <summary>
  2. /// Finds the longest connect region per color.
  3. /// </summary>
  4. /// <returns>Returns a pair that has the color and the count of the connected cells</returns>
  5. public static Tuple<int,int> FindLongestConnectedColor()
  6. {
  7. int[,] graph = {
  8. {1, 1, 1, 2,2,3},
  9. {1, 1, 1, 2,2,3},
  10. {1, 1, 1, 2,2,3}
  11. };
  12.  
  13. var graphRowsCount = graph.GetLength(0);
  14. var graphColumnsCount = graph.GetLength(1);
  15.  
  16. var visitedCellsPerColor = new Dictionary<int, HashSet<Tuple<int, int>>>();
  17.  
  18. // first int represents the color, second int represents the region cells' count
  19. var longestRegion = new Tuple<int, int>(-1, -1);
  20.  
  21.  
  22. for (int row = 0; row < graphRowsCount; row++)
  23. {
  24. for (int column = 0; column < graphColumnsCount; column++)
  25. {
  26. var color = graph[row, column];
  27.  
  28. if (!visitedCellsPerColor.ContainsKey(color))
  29. {
  30. visitedCellsPerColor.Add(color, new HashSet<Tuple<int, int>>());
  31. }
  32.  
  33. if (!visitedCellsPerColor[color].Contains(new Tuple<int, int>(row, column)))
  34. {
  35. var length = GetConnectedRegionLength(row, column, graph, visitedCellsPerColor);
  36. if (longestRegion.Item2 < length)
  37. {
  38. longestRegion = new Tuple<int, int>(color, length);
  39. }
  40. }
  41. }
  42. }
  43.  
  44. return longestRegion;
  45. }
  46.  
  47. private static int GetConnectedRegionLength(int row, int column, int[,] graph, Dictionary<int, HashSet<Tuple<int, int>>> visited)
  48. {
  49. var directionRow = new List<int> { -1, +1, 0, 0 };
  50. var directionColumn = new List<int> { 0, 0, +1, -1 };
  51.  
  52. var connectedCellsCount = 0;
  53.  
  54. var color = graph[row, column];
  55.  
  56. var q1 = new Queue<int>();
  57. var q2 = new Queue<int>();
  58.  
  59. q1.Enqueue(row);
  60. q2.Enqueue(column);
  61. visited[color].Add(new Tuple<int, int>(row, column));
  62. connectedCellsCount++;
  63.  
  64. while (q1.Any())
  65. {
  66. // current Row
  67. var cr = q1.Dequeue();
  68. // Current Column
  69. var cc = q2.Dequeue();
  70.  
  71. for (int a = 0; a < directionRow.Count; a++)
  72. {
  73. var newRow = cr + directionRow[a];
  74. var newColumn = cc + directionColumn[a];
  75.  
  76. if (newRow < 0 || newColumn < 0) continue;
  77. if (newRow >= graph.GetLength(0) || newColumn >= graph.GetLength(1)) continue;
  78. if (graph[newRow, newColumn] != color) continue;
  79. if (visited[color].Contains(new Tuple<int, int>(newRow, newColumn))) continue;
  80.  
  81. q1.Enqueue(newRow);
  82. q2.Enqueue(newColumn);
  83. visited[color].Add(new Tuple<int, int>(newRow, newColumn));
  84. connectedCellsCount++;
  85. }
  86. }
  87.  
  88. return connectedCellsCount;
  89. }
Add Comment
Please, Sign In to add comment