How to shallow copy and deep copy a jagged array using ToArray()?

40 Views Asked by At
int[] nm = Array.ConvertAll(Console.ReadLine().Split(),int.Parse);
int[][]graph = new int[nm[0]][];
int[][] meltedGraph = new int[nm[0]][];
for (int i = 0; i < nm[0]; i++)
{
    graph[i] = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
    // deep copy
    meltedGraph[i] = graph[i].ToArray();

}
// shallow copy
//meltedGraph = graph.ToArray();

    input
    
    5 7
    0 0 0 0 0 0 0
    0 2 4 5 3 0 0
    0 3 0 2 5 2 0
    0 7 6 2 4 0 0
    0 0 0 0 0 0 0
    
    3 3
    0 0 0
    0 0 0
    0 0 0

...

I am solving an algorithm problem, and I need to put the input values ​​into "graph" and "meltedGraph" like the code above. In that way, when accessing and inserting each row of a variable array through a loop statement, it becomes a deep copy. However, if you use ToArray() on the array itself without directly accessing the row, Shallow Copy occurs, and I wonder why.

0

There are 0 best solutions below