using System.Collections.Generic;
public int x1, y1, x2, y2;
public Line(int x1, int y1, int x2, int y2) {
public bool ConnectsTo(Line other) {
return x1 == other.x2 && y1 == other.y2 || x2 == other.x1 && y2 == other.y1;
public class LineGroupDetector {
public List<List<Line>> DetectGroups(List<Line> lines) {
Dictionary<Line, List<Line>> graph = BuildGraph(lines);
List<List<Line>> groups = new List<List<Line>>();
HashSet<Line> visited = new HashSet<Line>();
foreach (Line line in lines) {
if (!visited.Contains(line)) {
List<Line> group = new List<Line>();
TraverseGroup(line, graph, visited, group);
private Dictionary<Line, List<Line>> BuildGraph(List<Line> lines) {
Dictionary<Line, List<Line>> graph = new Dictionary<Line, List<Line>>();
foreach (Line line1 in lines) {
foreach (Line line2 in lines) {
if (line1 != line2 && line1.ConnectsTo(line2)) {
if (!graph.ContainsKey(line1)) {
graph[line1] = new List<Line>();
if (!graph.ContainsKey(line2)) {
graph[line2] = new List<Line>();
private void TraverseGroup(Line line, Dictionary<Line, List<Line>> graph, HashSet<Line> visited, List<Line> group) {
foreach (Line neighbor in graph[line]) {
if (!visited.Contains(neighbor)) {
TraverseGroup(neighbor, graph, visited, group);
public static void Main()
List<Line> lines = new List<Line>();
lines.Add(new Line(0, 0, 1, 1));
lines.Add(new Line(1, 1, 2, 2));
lines.Add(new Line(3, 3, 4, 4));
lines.Add(new Line(4, 4, 5, 5));
lines.Add(new Line(5, 5, 6, 6));
lines.Add(new Line(6, 6, 7, 7));
lines.Add(new Line(8, 8, 9, 9));
lines.Add(new Line(9, 9, 8, 8));
LineGroupDetector detector = new LineGroupDetector();
List<List<Line>> groups = detector.DetectGroups(lines);
for (int i = 0; i < groups.Count; i++) {
Console.WriteLine("Group " + (i + 1));
foreach (Line line in groups[i]) {
Console.WriteLine("(" + line.x1 + ", " + line.y1 + ") to (" + line.x2 + ", " + line.y2 + ")");