{"record":{"id":"49c808879f20d4c8","repo":"TheAlgorithms/C-Sharp","slug":"adjacency-matrix-must-be-square","errorCode":null,"errorMessage":"Adjacency matrix must be square!","messagePattern":"Adjacency matrix must be square!","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs","lineNumber":83,"sourceCode":"            }\n\n            mst[i, parent[i]] = adjacencyMatrix[i, parent[i]];\n            mst[parent[i], i] = adjacencyMatrix[i, parent[i]];\n        }\n\n        return mst;\n    }\n\n    /// <summary>\n    ///     Ensure that the given adjacency matrix represents a weighted undirected graph.\n    /// </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            }","sourceCodeStart":65,"sourceCodeEnd":101,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs#L65-L101","documentation":"Prim's MST algorithm (matrix variant) requires the adjacency matrix to be square: the element at [i,j] must be defined for all pairs of the same set of nodes, so GetLength(0) must equal GetLength(1). ValidateMatrix, invoked from Solve, throws ArgumentException when the two dimensions differ. A non-square matrix cannot represent a complete node-to-node weight table.","triggerScenarios":"Calling PrimMatrix.Solve with a float[,] whose first and second dimensions differ — e.g. constructing a rows x edges or nodes x (nodes-1) array, or accidentally transposing part of a rectangular array.","commonSituations":"Initializing the array with swapped dimension arguments (new float[n, m] instead of new float[n, n]); representing an edge list or incidence matrix instead of an adjacency matrix; resizing the node count but updating only one dimension.","solutions":["Ensure the array is created as new float[n, n] where n is the node count, with both dimensions equal.","Audit how the matrix is built; if you have an edge list, first convert it into a square n x n adjacency matrix.","Check for transposed/rectangular intermediate arrays and use a proper 2D square matrix for graph data.","Pre-validate in your own code: matrix.GetLength(0) == matrix.GetLength(1) before calling Solve."],"exampleFix":"// before\nvar adj = new float[nodeCount, edgeCount];\n\n// after\nvar adj = new float[nodeCount, nodeCount]; // must be square","handlingStrategy":"validation","validationCode":"static bool IsSquare(float[,] m) => m != null && m.GetLength(0) == m.GetLength(1);\nif (!IsSquare(adj)) throw new ArgumentException(\"adjacency matrix must be square\");","typeGuard":"static bool IsSquareMatrix(float[,] m) => m != null && m.GetLength(0) == m.GetLength(1);","tryCatchPattern":"try\n{\n    var mst = prim.Solve(adj);\n}\ncatch (ArgumentException ex) when (ex.Message == \"Adjacency matrix must be square!\")\n{\n    // rebuild as n x n matrix before retrying\n}","preventionTips":["Create adjacency matrices with new float[n, n] only","Convert edge lists to a square matrix before passing to the solver","Check GetLength(0) == GetLength(1) in tests for all fixtures","Watch for accidental rectangular intermediate arrays when resizing the graph"],"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"}