{"record":{"id":"7860afab9f96255a","repo":"TheAlgorithms/C-Sharp","slug":"matrix-must-be-square","errorCode":null,"errorMessage":"Matrix must be square!","messagePattern":"Matrix must be square!","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Graph/MinimumSpanningTree/Kruskal.cs","lineNumber":131,"sourceCode":"\n        foreach (var (node1, node2) in edges)\n        {\n            mst[node1].Add(node2, adjacencyList[node1][node2]);\n            mst[node2].Add(node1, adjacencyList[node1][node2]);\n        }\n\n        return mst;\n    }\n\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>","sourceCodeStart":113,"sourceCodeEnd":149,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Graph/MinimumSpanningTree/Kruskal.cs#L113-L149","documentation":"Kruskal's minimum-spanning-tree solver requires the graph as a square adjacency matrix (vertices x vertices). ValidateGraph throws ArgumentException(\"Matrix must be square!\") when adj.GetLength(0) != adj.GetLength(1) (Kruskal.cs:131). A non-square matrix cannot represent a weighted undirected graph, so the input is rejected before the algorithm runs.","triggerScenarios":"Calling Kruskal.Solve with a rectangular float[,] — e.g. a matrix built from data rows x feature columns, an adjacency list flattened into a matrix, or a matrix missing its last row/column after truncation.","commonSituations":"Loading a CSV/TSV where a row has a different column count than the row count, slicing an adjacency matrix and producing a rectangle, or constructing the matrix as [edges, vertices] instead of [vertices, vertices].","solutions":["Verify the matrix dimensions before calling Solve: adj.GetLength(0) == adj.GetLength(1).","Fix the matrix construction so each of the n vertices has exactly n entries (row i column j = edge weight i->j).","If data is rectangular, reshape or pad it into a square adjacency matrix (using infinity/no-edge sentinels for absent edges)."],"exampleFix":"// before\nvar adj = new float[numEdges, numVertices]; // rectangular\nKruskal.Solve(adj);\n// after\nvar n = numVertices;\nvar adj = new float[n, n];\nfor (int i = 0; i < n; i++)\n    for (int j = 0; j < n; j++)\n        adj[i, j] = weightBetween(i, j); // e.g. float.PositiveInfinity when no edge\nKruskal.Solve(adj);","handlingStrategy":"validation","validationCode":"if (adj.Rank != 2 || adj.GetLength(0) != adj.GetLength(1))\n    throw new ArgumentException($\"Adjacency matrix must be square, got {adj.GetLength(0)}x{adj.GetLength(1)}\");\nKruskal.Solve(adj);","typeGuard":"static bool IsSquareMatrix(float[,]? m) => m is not null && m.Rank == 2 && m.GetLength(0) == m.GetLength(1);","tryCatchPattern":"try\n{\n    var mst = Kruskal.Solve(adj);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"square\"))\n{\n    logger.LogError(ex, \"Adjacency matrix shape {Rows}x{Cols} is not square\", adj.GetLength(0), adj.GetLength(1));\n}","preventionTips":["Assert matrix dimensions right after loading/parsing the matrix, before any algorithm runs.","When importing from CSV, validate that row count equals column count and every row has the same width.","Build adjacency matrices as [n, n] with a documented no-edge sentinel (e.g. PositiveInfinity) instead of rectangular data arrays."],"tags":["argument-exception","matrix","minimum-spanning-tree","csharp"],"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"}