/// <summary> /// Compares this instance with a specified adjacency matrix. /// </summary> /// <param name="matrix">The specified adjacency matrix that this instantce is to be compared with.</param> /// <returns> /// Returns NULL if the two adjaceny matrices are identical. /// If the two adjacency matrices are different, return a List<int> containing the indexes of different vertices. /// </returns> public List <int> CompareTo(AdjacencyMatrix matrix) { bool isEqual = true; List <int> differentVertices = new List <int>(); if (matrix == null) { isEqual = false; for (int v = 0; v < GetSize(); v++) { if (this.IsVertexExisting(v)) { if (!differentVertices.Contains(v)) { differentVertices.Add(v); } } } differentVertices.Sort(); return(differentVertices); } for (int v = 0; v < GetSize(); v++) { if (this.IsVertexExisting(v) != matrix.IsVertexExisting(v)) { isEqual = false; if (!differentVertices.Contains(v)) { differentVertices.Add(v); } } } for (int row = 0; row < GetSize(); row++) { for (int col = 0; col < GetSize(); col++) { if (!this.GetEdge(row, col).Equals(matrix.GetEdge(row, col))) { isEqual = false; if (!differentVertices.Contains(row)) { differentVertices.Add(row); } } } } if (isEqual) { return(null); } else { differentVertices.Sort(); return(differentVertices); } }
/// <summary> /// Show the tag window of the vertex, and all its adjacenct edge information. /// </summary> private void FormVertexTag_Load(object sender, EventArgs e) { for (int finishingVertex = 0; finishingVertex < mapMatrix.GetSize(); finishingVertex++) { int startingVertex = mapMatrix.GetVertexIndex((sender as FormVertexTag).Text.Trim("Vertex ".ToCharArray())); if (mapMatrix.IsVertexExisting(finishingVertex) && finishingVertex != startingVertex) { (sender as FormVertexTag).AddVertexTagControl(finishingVertex); if (mapMatrix.ContainsEdge(startingVertex, finishingVertex)) { (sender as FormVertexTag).edgeControls[(sender as FormVertexTag).edgeControls.Count - 1].GetCheckBoxContainsEdge().Checked = true; (sender as FormVertexTag).edgeControls[(sender as FormVertexTag).edgeControls.Count - 1].GetTextBoxWeight().Text = mapMatrix.GetEdge(startingVertex, finishingVertex).ToString(); } } } }
// Linked list maintenance (Group A) is implemented here /// <summary> /// Copies and initialises all the vertices into the Union-Find structural list. /// </summary> private void InitialiseUnionFind() { for (int vertex = 0; vertex < mapMatrix.GetSize(); vertex++) { if (mapMatrix.IsVertexExisting(vertex)) { unionFindVertices.Add(new UnionFind()); unionFindVertices[unionFindVertices.Count() - 1].SetVertex(vertex); unionFindVertices[unionFindVertices.Count() - 1].SetLeader(vertex); unionFindVertices[unionFindVertices.Count() - 1].SetPrev(-1); unionFindVertices[unionFindVertices.Count() - 1].SetHead(vertex); unionFindVertices[unionFindVertices.Count() - 1].SetTail(vertex); unionFindVertices[unionFindVertices.Count() - 1].SetCount(1); } } }
private void LabelVertexName_Click(object sender, EventArgs e) { // Step 1 operation on graph - Choose starting vertex if (currentStep == 1 && !buttonNext.Enabled) { int vStart = Convert.ToInt32(Convert.ToChar((sender as Label).Text) - 'A'); InitialiseSingleSource(vStart); permanentVertices.Add(vStart); for (int v = 0; v < mapMatrix.GetSize(); v++) { if (mapMatrix.IsVertexExisting(v) && v != vStart) { temporaryVertices.Add(v); } } labelInformation.Text = "You have chosen vertex " + (sender as Label).Text + ".\n" + "It has been made permanent by being given permanent label 0 and order label 1."; foreach (DijkstraVertexLabel vertex in vertices) { if (vertex.labelVertexName.Equals(sender as Label)) { vertex.Finalise(0, 1); vertex.FocusOn(); break; } } currentStep = 2; buttonNext.Enabled = true; } // Step 3 operation on graph - Choose one of the candidate vertices else if (currentStep == 3 && !buttonNext.Enabled) { int newVertex = Convert.ToInt32(Convert.ToChar((sender as Label).Text) - 'A'); if (candidateVertices.Contains(newVertex)) { temporaryVertices.Remove(newVertex); permanentVertices.Add(newVertex); labelInformation.Text = "You have chosen vertex " + (sender as Label).Text + ".\n" + "Therefore it has been made permanent with order " + permanentVertices.Count.ToString() + "."; foreach (DijkstraVertexLabel vertex in vertices) { if (vertex.GetNumberIndex() == newVertex) { vertex.Finalise(min, permanentVertices.Count); } else { vertex.FocusOff(); } } currentStep = 4; buttonNext.Enabled = true; } } // Step 4 operation on graph - Choose one finishing vertex and show the shortest path // Graph/Tree Traversal (Group A) is implemented here. else if (currentStep == 4 && buttonNext.Text == "Close") { int vFinish = Convert.ToInt32(Convert.ToChar((sender as Label).Text) - 'A'); if (vFinish != permanentVertices[0]) { labelInformation.Text = "You have chosen vertex " + (sender as Label).Text + ".\n" + "The shortest route from vertex " + Convert.ToChar(permanentVertices[0] + 'A').ToString() + " to " + (sender as Label).Text + " has been found using 'trace back' method.\n" + "You can click on other vertices to see their shortest routes and distances."; labelFinalResult.Text = "Shortest route: "; List <int> shortestPath = new List <int> { vFinish }; int i = vFinish; while (dijkstraMap[i].prev != -1) { labelFinalResult.Text += Convert.ToChar(i + 'A').ToString() + "←"; shortestPath.Add(dijkstraMap[i].prev); i = dijkstraMap[i].prev; } shortestPath.Reverse(); labelFinalResult.Text += Convert.ToChar(permanentVertices[0] + 'A').ToString() + " ("; foreach (int vertex in shortestPath) { labelFinalResult.Text += Convert.ToChar(vertex + 'A').ToString(); } labelFinalResult.Text += ")\nShortest distance = "; foreach (DijkstraVertexLabel vertex in vertices) { if (vertex.labelVertexName.Equals(sender as Label)) { labelFinalResult.Text += vertex.GetFinalLabel().ToString(); break; } } labelFinalResult.Visible = true; foreach (DijkstraVertexLabel vertex in vertices) { if (shortestPath.Contains(vertex.GetNumberIndex())) { vertex.FocusOn(); } else { vertex.FocusOff(); } } for (int v1 = 0; v1 < mapMatrix.GetSize(); v1++) { for (int v2 = 0; v2 < mapMatrix.GetSize(); v2++) { if (mapMatrix.ContainsEdge(v1, v2)) { DirectedEdgeFocusOff(v1, v2); exampleGraph.LabelFocusOff(v1, v2); } } } for (int vertexIndex = 1; vertexIndex < shortestPath.Count; vertexIndex++) { int v1 = shortestPath[vertexIndex - 1]; int v2 = shortestPath[vertexIndex]; if (mapMatrix.ContainsEdge(v2, v1) && mapMatrix.GetEdge(v1, v2) == mapMatrix.GetEdge(v2, v1)) { UndirectedEdgeFocusOn(v1, v2); exampleGraph.LabelFocusOn(v1, v2); exampleGraph.LabelFocusOn(v2, v1); } else { DirectedEdgeFocusOn(v1, v2); exampleGraph.LabelFocusOn(v1, v2); } } currentStep = 4; } } }
// Graph/Tree Traversal (Group A) is implemented here. private void ButtonNext_Click(object sender, EventArgs e) { if (buttonNext.Text == "Close") { this.Close(); } else { labelInformation.Visible = true; // Step 1 operation if (currentStep == 1) { // Highlight current step label1.ForeColor = Color.Red; labelStep1.ForeColor = Color.Red; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; // Initialise Prim's algorithm for (int i = 0; i < mapMatrix.GetSize(); i++) { if (mapMatrix.IsVertexExisting(i)) { remainingVertices.Add(i); } } labelInformation.Text = "Please pick a vertex of your choice:\nPlease click on the vertex of the graph."; buttonNext.Enabled = false; } // Step 2 operation else if (currentStep == 2) { // Highlight current step label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = Color.Red; labelStep2.ForeColor = Color.Red; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; // Find minimum value of edge weight and candidate edges double min = Double.MaxValue; List <int[]> candidateEdges = new List <int[]>(); foreach (int i in visitedVertices) { foreach (int j in remainingVertices) { if (mapMatrix.ContainsEdge(i, j) && mapMatrix.GetEdge(i, j) < min) // Find minimum value of edge weight { min = mapMatrix.GetEdge(i, j); } } } foreach (int i in visitedVertices) { foreach (int j in remainingVertices) { if (mapMatrix.ContainsEdge(i, j) && mapMatrix.GetEdge(i, j) == min) // Find candidate edges { candidateEdges.Add(new int[2] { i, j }); } } } // More than two candidate edges - User operation required if (candidateEdges.Count >= 2) { // Show explanation labelInformation.Text = "Edges "; foreach (int[] edge in candidateEdges) { labelInformation.Text += Convert.ToChar(edge[0] + 'A').ToString() + Convert.ToChar(edge[1] + 'A').ToString() + ", "; } labelInformation.Text = labelInformation.Text.TrimEnd(", ".ToCharArray()); labelInformation.Text += " have the same weight (" + min.ToString() + "). Please pick one of your choice:\n" + "Please click on the vertex or the weight."; // Highlight candidate edges for (int i = 0; i < candidateEdges.Count; i++) { int v1 = Math.Min(candidateEdges[i][0], candidateEdges[i][1]); int v2 = Math.Max(candidateEdges[i][0], candidateEdges[i][1]); string labelName = "label" + Convert.ToChar(v1 + 'A').ToString() + Convert.ToChar(v2 + 'A').ToString(); foreach (Label label in exampleGraph.labelWeights) { if (label.Name == labelName) { label.ForeColor = Color.Red; break; } } foreach (Vertex vertex in vertices) { if (vertex.GetNumberIndex() == candidateEdges[i][1]) { vertex.labelName.ForeColor = Color.Red; break; } } } currentStep = 2; buttonNext.Enabled = false; } // Only one candidate edge avaliable - No user operation needed else { // Show explanation int[] newEdge = new int[2] { candidateEdges[0][0], candidateEdges[0][1] }; labelInformation.Text = "Edge " + Convert.ToChar(candidateEdges[0][0] + 'A').ToString() + Convert.ToChar(candidateEdges[0][1] + 'A').ToString() + " has the minimum weight joining a vertex already included to a vertex not already included (" + min.ToString() + ")," + " therefore it has been added to the Minimum Spanning Tree."; // Update Prim's algorithm foreach (Vertex vertex in vertices) { if (vertex.GetNumberIndex() == newEdge[1]) { weightMST += min; labelTotalWeight.Text += min.ToString() + " + "; visitedVertices.Add(newEdge[1]); remainingVertices.Remove(newEdge[1]); EdgeFocusOn(newEdge[0], newEdge[1]); exampleGraph.LabelFocusOn(newEdge[0], newEdge[1]); currentStep = 3; break; } } } } // Step 3 operation else // if (currentStep == 3) { // Highlight current steps label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = Color.Red; labelStep3.ForeColor = Color.Red; // Check if Prim's algorithm has finished if (remainingVertices.Any()) { labelInformation.Text = "We have not yet formed a Minimum Spanning Tree, so go back to STEP 2."; currentStep = 2; } else { labelInformation.Text = "Now we have picked " + (mapMatrix.Count() - 1).ToString() + " edges and has formed a Minimum Spanning Tree.\nTherefore Prim's algorithm has finished."; labelTotalWeight.Text = labelTotalWeight.Text.TrimEnd(" + ".ToCharArray()); labelTotalWeight.Text += " = " + weightMST.ToString(); labelTotalWeight.Visible = true; buttonNext.Text = "Close"; } } } }
public FormPrimOnMatrix(int accountID, string username, string accountName, string accountType, int example) { InitializeComponent(); // Show account name on the account menu. this.accountMenu.accountID = accountID; this.accountMenu.username = username; this.accountMenu.labelAccountName.Text = accountName; this.accountMenu.accountType = accountType; this.example = example; // Select the correct example graph to perform the demonstration. if (example == 1) { exampleGraph = new MinimumSpanningTreeExample1(this.panelGraph); } else { exampleGraph = new MinimumSpanningTreeExample2(this.panelGraph); } // Initialise the example graph. vertices = exampleGraph.GetVertices(); mapMatrix = exampleGraph.GetMatrix(); // Initialise the table for the example graph. for (int i = 0; i <= mapMatrix.Count(); i++) { DataGridViewColumn newColumn = new DataGridViewColumn { CellTemplate = new DataGridViewTextBoxCell(), SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable, Width = 60 }; if (i == 0) { newColumn.Width = 41; } dataGridViewGraph.Columns.Add(newColumn); } int count = 1; for (int i = 0; i < mapMatrix.GetSize(); i++) { if (mapMatrix.IsVertexExisting(i)) { dataGridViewGraph.Columns[count].HeaderText = Convert.ToChar('A' + i).ToString(); dataGridViewGraph.Columns[count].Name = "Column" + dataGridViewGraph.Columns[count].HeaderText; count++; } } count = 0; this.dataGridViewGraph.RowCount = mapMatrix.Count(); for (int i = 0; i < mapMatrix.GetSize(); i++) { if (mapMatrix.IsVertexExisting(i)) { this.dataGridViewGraph[0, count++].Value = (Convert.ToChar('A' + i)).ToString(); } } for (int col = 1; col <= mapMatrix.Count(); col++) { for (int row = 0; row < mapMatrix.Count(); row++) { int vStartIndex = mapMatrix.GetVertexIndex(dataGridViewGraph.Columns[col].HeaderText); int vFinishIndex = mapMatrix.GetVertexIndex(this.dataGridViewGraph[0, row].Value.ToString()); if (mapMatrix.ContainsEdge(vStartIndex, vFinishIndex)) { this.dataGridViewGraph[col, row].Value = mapMatrix.GetEdge(vStartIndex, vFinishIndex); } else { this.dataGridViewGraph[col, row].Value = "-"; } } } }
// Graph/Tree Traversal (Group A) is implemented here. private void ButtonNext_Click(object sender, EventArgs e) { if (buttonNext.Text == "Close") { this.Close(); } else { labelInformation.Visible = true; double min; // Step 1 operation if (currentStep == 1) { // Highlight current step label1.ForeColor = Color.Red; labelStep1.ForeColor = Color.Red; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; label4.ForeColor = SystemColors.ControlText; labelStep4.ForeColor = SystemColors.ControlText; label5.ForeColor = SystemColors.ControlText; labelStep5.ForeColor = SystemColors.ControlText; // Initialise Prim's algorithm for (int i = 0; i < mapMatrix.GetSize(); i++) { if (mapMatrix.IsVertexExisting(i)) { remainingVertices.Add(i); } } labelInformation.Text = "Please pick a vertex of your choice:\nPlease click on the headers of the tableau."; buttonNext.Enabled = false; } // Step 2 operation else if (currentStep == 2) { // Highlight current step label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = Color.Red; labelStep2.ForeColor = Color.Red; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; label4.ForeColor = SystemColors.ControlText; labelStep4.ForeColor = SystemColors.ControlText; label5.ForeColor = SystemColors.ControlText; labelStep5.ForeColor = SystemColors.ControlText; // Find minimum value of edge weight and candidate edges min = double.MaxValue; candidateEdges.Clear(); foreach (int i in visitedVertices) { foreach (int j in remainingVertices) { if (mapMatrix.ContainsEdge(i, j) && mapMatrix.GetEdge(i, j) < min) // Find minimum value of edge weight { min = mapMatrix.GetEdge(i, j); } } } foreach (int i in visitedVertices) { foreach (int j in remainingVertices) { if (mapMatrix.ContainsEdge(i, j) && mapMatrix.GetEdge(i, j) == min) // Find candidate edges { candidateEdges.Add(new int[2] { i, j }); } } } // Show candidate edges on the table for (int i = 0; i < candidateEdges.Count; i++) { char v1 = Convert.ToChar(candidateEdges[i][0] + 'A'); char v2 = Convert.ToChar(candidateEdges[i][1] + 'A'); for (int col = 1; col < dataGridViewGraph.ColumnCount; col++) { if (dataGridViewGraph.Columns[col].HeaderText[0] == v1) { for (int row = 0; row < dataGridViewGraph.RowCount; row++) { if (dataGridViewGraph[0, row].Value.ToString() == v2.ToString()) { dataGridViewGraph[col, row].Style.ForeColor = Color.Red; dataGridViewGraph[col, row].Style.SelectionForeColor = Color.Red; } } } } } // More than two candidate edges - User operation required if (candidateEdges.Count >= 2) { labelInformation.Text = "Edges "; foreach (int[] edge in candidateEdges) { labelInformation.Text += Convert.ToChar(edge[0] + 'A').ToString() + Convert.ToChar(edge[1] + 'A').ToString() + ", "; } labelInformation.Text = labelInformation.Text.TrimEnd(", ".ToCharArray()); labelInformation.Text += " have the same weight (" + min.ToString() + "). Please pick one of your choice:\n" + "Please click on the weights in the tableau."; currentStep = 2; buttonNext.Enabled = false; } // Only one candidate edge avaliable - No user operation needed else if (candidateEdges.Count == 1) { newEdge = new int[2] { candidateEdges[0][0], candidateEdges[0][1] }; labelInformation.Text = "Edge " + Convert.ToChar(candidateEdges[0][0] + 'A').ToString() + Convert.ToChar(candidateEdges[0][1] + 'A').ToString() + " has the minimum weight from the uncircled entries in the marked column(s) (" + min.ToString() + ")," + " therefore it has been chosen."; currentStep = 3; } // No candidate edge found - Algorithm about to finish else { labelInformation.Text = ""; currentStep = 3; } } // Step 3 operation else if (currentStep == 3) { // Highlight current step label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = Color.Red; labelStep3.ForeColor = Color.Red; label4.ForeColor = SystemColors.ControlText; labelStep4.ForeColor = SystemColors.ControlText; label5.ForeColor = SystemColors.ControlText; labelStep5.ForeColor = SystemColors.ControlText; // Check if Prim's algorithm has finished if (candidateEdges.Count == 0) { labelInformation.Text = "There is no available entry to be chosen, and therefore Prim's algorithm has finished.\n" + "We have found a Minimum Spanning Tree."; labelTotalWeight.Text = labelTotalWeight.Text.TrimEnd(" + ".ToCharArray()); labelTotalWeight.Text += " = " + weightMST.ToString(); labelTotalWeight.Visible = true; buttonNext.Text = "Close"; } else { labelInformation.Text += "\nNow that we have found an entry, we should go to STEP 4."; currentStep = 4; } } // Step 4 operation else if (currentStep == 4) { // Highlight current step label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; label4.ForeColor = Color.Red; labelStep4.ForeColor = Color.Red; label5.ForeColor = SystemColors.ControlText; labelStep5.ForeColor = SystemColors.ControlText; // Update Prim's algorithm and show demonstration labelInformation.Text = ""; weightMST += mapMatrix.GetEdge(newEdge[0], newEdge[1]); labelTotalWeight.Text += mapMatrix.GetEdge(newEdge[0], newEdge[1]).ToString() + " + "; visitedVertices.Add(newEdge[1]); remainingVertices.Remove(newEdge[1]); EdgeFocusOn(newEdge[0], newEdge[1]); exampleGraph.LabelFocusOn(newEdge[0], newEdge[1]); char v1 = Convert.ToChar(newEdge[0] + 'A'); char v2 = Convert.ToChar(newEdge[1] + 'A'); for (int col = 1; col < dataGridViewGraph.ColumnCount; col++) { for (int row = 0; row < dataGridViewGraph.RowCount; row++) { if (dataGridViewGraph.Columns[col].HeaderText[0] == v1 && dataGridViewGraph[0, row].Value.ToString() == v2.ToString()) { dataGridViewGraph.Columns[row + 1].HeaderCell.Style.ForeColor = Color.Red; dataGridViewGraph.Columns[row + 1].HeaderCell.Style.SelectionForeColor = Color.Red; dataGridViewGraph.Columns[row + 1].HeaderCell.Value = dataGridViewGraph.Columns[row + 1].HeaderCell.Value.ToString() + " " + visitedVertices.Count.ToString(); dataGridViewGraph[col, row].Style.Font = boldFont; dataGridViewGraph[col, row].Style.ForeColor = Color.Red; dataGridViewGraph[col, row].Style.SelectionForeColor = Color.Red; } else if (dataGridViewGraph[col, row].Style.Font != boldFont) { dataGridViewGraph[col, row].Style.ForeColor = SystemColors.ControlText; dataGridViewGraph[col, row].Style.SelectionForeColor = SystemColors.ControlText; if (visitedVertices.Contains(Convert.ToInt32(Convert.ToChar(dataGridViewGraph[0, row].Value) - 'A'))) { dataGridViewGraph[col, row].Style.Font = strikeoutFont; } } } } currentStep = 5; } // Step 5 operation else // if (currentStep == 5) { // Highlight current step label1.ForeColor = SystemColors.ControlText; labelStep1.ForeColor = SystemColors.ControlText; label2.ForeColor = SystemColors.ControlText; labelStep2.ForeColor = SystemColors.ControlText; label3.ForeColor = SystemColors.ControlText; labelStep3.ForeColor = SystemColors.ControlText; label4.ForeColor = SystemColors.ControlText; labelStep4.ForeColor = SystemColors.ControlText; label5.ForeColor = Color.Red; labelStep5.ForeColor = Color.Red; // Refresh and go to Step 2 labelInformation.Text = ""; currentStep = 2; } } }