修订版:我使用经典的双色算法测试二分性的新解决方案。这似乎给出了最佳表现:
var colors = new Dictionary<int, int>();
var min = graphDict.Keys.First();
var max = graphDict.Keys.Last();
for (var i = min; i <= max; i++)
{
colors[i] = -1;
}
var terminate = false;
var q = new Queue<int>();
var curr = min;
colors[curr] = 0;
q.Enqueue(curr);
while (q.Count > 0)
{
curr = q.Dequeue();
var adjList = graphDict[curr];
foreach (var adj in adjList)
{
if (colors[adj] == colors[curr])
{
terminate = true;
break;
}
else if (colors[adj] == -1)
{
colors[adj] = 1 - colors[curr];
q.Enqueue(adj);
}
}
}
Console.Write($"{(terminate ? -1 : 1)} ");