我的二分算法可以改进吗?

时间:2016-12-01 06:38:58

标签: graph bipartite

修订版:我使用经典的双色算法测试二分性的新解决方案。这似乎给出了最佳表现:

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)} ");

0 个答案:

没有答案