There is a good deal of confusion and misinformation in this thread. In fact, there is a method of avoiding initialization costs of adjacency matrices (and any array in general). However, it is not possible to use the method with Java primitives since they are initialized with default values under the hood.
Suppose you could create an array data[0..n]
that is not auto-initialized. To start, it is filled with junk from whatever was previously in memory. If we don't want to spend O(n) time overwriting it, we need some way to differentiate the good data we add from junk data.
The "trick" is to use an auxiliary stack that tracks cells containing good data. The first time we write to data[i]
, we add index i
to the stack. Since a stack only grows as we add to it, it never contains any junk we need to worry about.
Now whenever we access data[k]
, we can check if its junk or not by scanning the stack for k
. But that would take O(n) time for each read, defeating the point of an array in the first place!
To solve this, we make another auxiliary array stack_check[0..n]
that also starts full of junk. This array contains pointers to elements in the stack. Now when we first write to data[i]
, we push i
onto the stack and set stack_check[i]
to point to the new stack element.
If data[k]
is good data, then stack_check[k]
points to a stack element holding k
. If data[k]
is junk, then the junk value of stack_check[k]
either points outside of the stack or points to some stack element besides k
(since k
was never put on the stack). Checking this property only takes O(1) time so our array access is still fast.
Bringing it all together, we can create our array and helper structures in O(1) time by letting them be full of junk. On each read and write, we check if the given cell contains junk in O(1) time using our helpers. If we are writing over junk, we update our helper structures to mark the cell as valid data. If we read junk, we can handle it in whatever way is appropriate for the given problem. For example, we could return a default value like 0 (now you can't even tell we didn't initialize it!) or maybe throw an exception.