Следующий код создаст матрицу смежности данной матрицы смежности, если она является бипатите (только бипатитные графики имеют матрицу смежности.) Если заданный граф не является бипатите, метод GetBiadjacencyMatrix() возвращает значение null.
Graph of the provided sample including its biadjacency matrix http://www.freeimagehosting.net/image.php?10e9b6a746.jpg
Не может видеть изображение? Click here
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; }
}
}
Не совсем то, что я хотел услышать, но, конечно, верно. :-) Спасибо за урок. –