{"record":{"id":"c0a30cde4a6aec8d","repo":"TheAlgorithms/C-Sharp","slug":"adjacency-matrix-must-be-symmetric","errorCode":null,"errorMessage":"Adjacency matrix must be symmetric!","messagePattern":"Adjacency matrix must be symmetric!","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs","lineNumber":94,"sourceCode":"    /// </summary>\n    /// <param name=\"adjacencyMatrix\">Adjacency matric to check.</param>\n    private static void ValidateMatrix(float[,] adjacencyMatrix)\n    {\n        // Matrix should be square\n        if (adjacencyMatrix.GetLength(0) != adjacencyMatrix.GetLength(1))\n        {\n            throw new ArgumentException(\"Adjacency matrix must be square!\");\n        }\n\n        // Graph needs to be undirected and connected\n        for (var i = 0; i < adjacencyMatrix.GetLength(0); i++)\n        {\n            var connection = false;\n            for (var j = 0; j < adjacencyMatrix.GetLength(0); j++)\n            {\n                if (Math.Abs(adjacencyMatrix[i, j] - adjacencyMatrix[j, i]) > 1e-6)\n                {\n                    throw new ArgumentException(\"Adjacency matrix must be symmetric!\");\n                }\n\n                if (!connection && float.IsFinite(adjacencyMatrix[i, j]))\n                {\n                    connection = true;\n                }\n            }\n\n            if (!connection)\n            {\n                throw new ArgumentException(\"Graph must be connected!\");\n            }\n        }\n    }\n\n    /// <summary>\n    ///     Determine which node should be added next to the MST.\n    /// </summary>","sourceCodeStart":76,"sourceCodeEnd":112,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs#L76-L112","documentation":"The matrix-based Prim solver requires an undirected graph, meaning the adjacency matrix must be symmetric: adjacencyMatrix[i,j] must equal adjacencyMatrix[j,i] (within 1e-6) for every pair of nodes. ValidateMatrix, called from Solve, throws ArgumentException on the first asymmetric pair it encounters. Asymmetric weights would give different edge costs depending on traversal direction, breaking Prim's correctness.","triggerScenarios":"Calling PrimMatrix.Solve with a square float[,] where at least one pair adj[i,j] and adj[j,i] differs by more than 1e-6 — typically because only the upper or lower triangle was filled, or directed weights were written per direction.","commonSituations":"Loading a directed graph's weight matrix directly into the solver; filling only half the matrix as an optimization; generating matrices with floating-point computations that are not order-symmetric; typos in hand-written test data.","solutions":["Mirror every weight: after setting adj[i,j], set adj[j,i] to the same value, or add a symmetrization loop over i<j before calling Solve.","If the source graph is directed, convert to undirected by consistently combining each directional pair (e.g. take the min) before invoking the solver.","Watch float precision: values must agree within 1e-6; recompute or round both cells from the same source value if drift is the issue.","Pre-scan in caller code for the first (i,j) with Math.Abs(adj[i,j]-adj[j,i]) > 1e-6 to find the offending entry."],"exampleFix":"// before\nadj[2, 5] = 7.3f;\n\n// after\nadj[2, 5] = 7.3f;\nadj[5, 2] = 7.3f; // keep both cells equal","handlingStrategy":"validation","validationCode":"static bool IsSymmetric(float[,] adj)\n{\n    for (int i = 0; i < adj.GetLength(0); i++)\n        for (int j = i + 1; j < adj.GetLength(1); j++)\n            if (Math.Abs(adj[i, j] - adj[j, i]) > 1e-6)\n                return false;\n    return true;\n}\nif (!IsSymmetric(adj)) throw new ArgumentException(\"adjacency matrix is not symmetric\");","typeGuard":"static bool IsUndirectedWeightMatrix(float[,] adj) =>\n    adj != null && adj.GetLength(0) == adj.GetLength(1) && IsSymmetric(adj);","tryCatchPattern":"try\n{\n    var mst = prim.Solve(adj);\n}\ncatch (ArgumentException ex) when (ex.Message == \"Adjacency matrix must be symmetric!\")\n{\n    // symmetrize the matrix, then retry\n}","preventionTips":["Assign both adj[i,j] and adj[j,i] whenever a weight is set","Symmetrize (copy upper triangle to lower or vice versa) as a final build step","Beware float precision: derive both cells from one computed value","Assert symmetry in unit tests for every fixture matrix"],"tags":["csharp","graph","mst","adjacency-matrix","input-validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}