次のコードは、指定された隣接行列がバイパタイトの場合、その隣接行列を作成します (バイパタイト グラフのみがバイ隣接行列を持ちます)。指定されたグラフがバイパタイトでない場合、GetBiadjacencyMatrix() メソッドは null を返します。
Biadjacency マトリックスを含む提供されたサンプルのグラフ http://www.freeimagehosting.net/image.php?10e9b6a746.jpg
画像が見えませんか?ここをクリック
public class Matrix
{
private void Usage()
{
int[,] AdjacencyMatrix = new int[,] {
{0, 1, 1, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 1, 1, 1, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 1, 0}
};
int[,] BiadjacencyMatrix = GetBiadjacencyMatrix(AdjacencyMatrix);
}
public static int[,] GetBiadjacencyMatrix(int[,] adjacencyMatrix)
{
int NodeCount = adjacencyMatrix.GetLength(0);
NodeInfo[] Nodes = new NodeInfo[NodeCount];
for (int c = NodeCount - 1; c >= 0; c--)
Nodes[c] = new NodeInfo(c);
if (ColorNode(adjacencyMatrix, Nodes, 0, 1, -1) != NodeCount)
return null; // Given graph is not bipatite.
int Part1Count = 0, Part2Count = 0;
foreach (NodeInfo Node in Nodes)
Node.IndexInPart = Node.PartID == 1 ? Part1Count++ : Part2Count++;
int[,] ToReturn = new int[Part1Count, Part2Count];
foreach (NodeInfo NodeInPart1 in Nodes)
if (NodeInPart1.PartID == 1)
foreach (NodeInfo NodeInPart2 in Nodes)
if (NodeInPart2.PartID == 2)
ToReturn[NodeInPart1.IndexInPart, NodeInPart2.IndexInPart]
= adjacencyMatrix[NodeInPart1.IndexInGraph, NodeInPart2.IndexInGraph];
return ToReturn;
}
private static int ColorNode(int[,] adjacencyMatrix, NodeInfo[] nodes, int currentNode, int currentPart, int parentNode)
{
if (nodes[currentNode].PartID != -1)
return nodes[currentNode].PartID != currentPart ? -1 : 0;
int ToReturn = 1;
nodes[currentNode].PartID = currentPart;
for (int c = nodes.Length - 1; c >= 0; c--)
if (adjacencyMatrix[currentNode, c] != 0 && c != parentNode)
{
int More = ColorNode(adjacencyMatrix, nodes, c, currentPart == 1 ? 2 : 1, currentNode);
if (More == -1) return -1;
ToReturn += More;
}
return ToReturn;
}
}
public class NodeInfo
{
private int _IndexInGraph;
private int _PartID;
private int _IndexInPart;
private bool _IsVisited;
public NodeInfo(int indexInGraph)
{
_IndexInGraph = indexInGraph;
_PartID = -1;
_IndexInPart = -1;
_IsVisited = false;
}
public int IndexInGraph
{
get { return _IndexInGraph; }
set { _IndexInGraph = value; }
}
public int PartID
{
get { return _PartID; }
set { _PartID = value; }
}
public int IndexInPart
{
get { return _IndexInPart; }
set { _IndexInPart = value; }
}
public bool IsVisited
{
get { return _IsVisited; }
set { _IsVisited = value; }
}
}