{"record":{"id":"fc9a70838fca911d","repo":"TheAlgorithms/C-Sharp","slug":"matrix-must-be-symmetric","errorCode":null,"errorMessage":"Matrix must be symmetric!","messagePattern":"Matrix must be symmetric!","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Graph/MinimumSpanningTree/Kruskal.cs","lineNumber":140,"sourceCode":"\n    /// <summary>\n    ///     Ensure that the given graph is undirected.\n    /// </summary>\n    /// <param name=\"adj\">Adjacency matrix of graph to check.</param>\n    private static void ValidateGraph(float[,] adj)\n    {\n        if (adj.GetLength(0) != adj.GetLength(1))\n        {\n            throw new ArgumentException(\"Matrix must be square!\");\n        }\n\n        for (var i = 0; i < adj.GetLength(0) - 1; i++)\n        {\n            for (var j = i + 1; j < adj.GetLength(1); j++)\n            {\n                if (Math.Abs(adj[i, j] - adj[j, i]) > 1e-6)\n                {\n                    throw new ArgumentException(\"Matrix must be symmetric!\");\n                }\n            }\n        }\n    }\n\n    /// <summary>\n    ///     Ensure that the given graph is undirected.\n    /// </summary>\n    /// <param name=\"adj\">Adjacency list of graph to check.</param>\n    private static void ValidateGraph(Dictionary<int, float>[] adj)\n    {\n        for (var i = 0; i < adj.Length; i++)\n        {\n            foreach (var edge in adj[i])\n            {\n                if (!adj[edge.Key].ContainsKey(i) || Math.Abs(edge.Value - adj[edge.Key][i]) > 1e-6)\n                {\n                    throw new ArgumentException(\"Graph must be undirected!\");","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Graph/MinimumSpanningTree/Kruskal.cs#L122-L158","documentation":"Kruskal's MST solver only accepts an adjacency matrix representing an undirected weighted graph, so it requires adj[i,j] == adj[j,i] for every pair of nodes (within a 1e-6 tolerance). ValidateGraph, called from Solve, throws this ArgumentException as soon as any asymmetric pair of cells is found. A symmetric matrix is the matrix representation of an undirected graph; an asymmetric one silently defines different edge weights depending on direction, which would make the MST result ill-defined.","triggerScenarios":"Calling Kruskal.Solve with a float[,] adjacency matrix where adj[i,j] differs from adj[j,i] by more than 1e-6 for at least one pair i<j — e.g. setting only the upper (or lower) triangle of the matrix, or assigning direction-dependent weights.","commonSituations":"Building the matrix from a directed edge list and forgetting to mirror each edge; filling only half the matrix as an optimization without expanding it; a data pipeline that merges directed and undirected edges; rounding/typo when hand-authoring small test matrices.","solutions":["Fix the input so every weight is mirrored: after filling adj[i,j], also set adj[j,i] to the same value (or run a symmetrization pass adj[j,i] = adj[i,j] before calling Solve).","If your graph is genuinely directed, this algorithm is not applicable — use a different algorithm or convert the graph to undirected by taking min/max of the two directional weights consistently.","Check for floating-point noise: if the asymmetry is only ~1e-6 or smaller, the check already tolerates it; larger drift means the values were computed differently and should be rounded or computed symmetrically.","Add a pre-validation pass in your own code that reports which (i,j) pair is asymmetric to pinpoint the bad entry."],"exampleFix":"// before\nadj[0, 1] = 4f;\n\n// after\nadj[0, 1] = 4f;\nadj[1, 0] = 4f; // mirror every edge","handlingStrategy":"validation","validationCode":"static bool IsSymmetric(float[,] adj)\n{\n    for (int i = 0; i < adj.GetLength(0) - 1; 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 IsSquareSymmetricMatrix(float[,] adj) =>\n    adj != null && adj.GetLength(0) == adj.GetLength(1) && IsSymmetric(adj);","tryCatchPattern":"try\n{\n    var mst = kruskal.Solve(adj);\n}\ncatch (ArgumentException ex) when (ex.Message == \"Matrix must be symmetric!\")\n{\n    // symmetrize or report the asymmetric input to the caller\n}","preventionTips":["Always mirror an edge in both cells when building the matrix","Add a symmetrization pass as the last build step before calling Solve","Assert symmetry in unit tests for every fixture matrix","Keep one source of truth per weight and assign both cells from it"],"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"}