Problem
There is an m x n
binary grid matrix
with all the values set 0
initially. Design an algorithm to randomly pick an index (i, j)
where matrix[i][j] == 0
and flips it to 1
. All the indices (i, j)
where matrix[i][j] == 0
should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.
Implement the Solution
class:
Solution(int m, int n)
Initializes the object with the size of the binary matrixm
andn
.int[] flip()
Returns a random index[i, j]
of the matrix wherematrix[i][j] == 0
and flips it to1
.void reset()
Resets all the values of the matrix to be0
.
Examples
Example 1:
|
|
Solution
Method 1 - Treat 2D Array as 1D Array and Use Fisher Yates
We model the matrix as a 1D array with an initial size of row * cols
. For each flip, randomly choose an index from 0 to size-1
and flip it. Once an element is flipped, reduce the total count by 1:
|
|
Next, swap the flipped element with the tail element (index: size-1
), record this mapping (key: original index, value: tail index) in a Map, and decrease the size:
|
|
In subsequent flips, if the same index is picked, use the map to find the actual element stored at that index:
|
|
Code
|
|
Dry Run and Explanation
There are only 3 possible scenarios.
For instance, if row = 2
, cols = 3
, and total = 6
:
-
The randomly generated number is the last one:
- Sequence:
0 1 2 3 4 5 6
- Random value:
r = 6
total
is now5
6
is not in themap
, thusx = 6
- Update
map
withmap[6] = 5
- This is straightforward. In future, numbers will be generated between
0-5
, ensuring6
is not repeated. - Chosen value:
{6}
- Sequence:
-
The randomly generated number hasn’t appeared before:
- Remaining numbers:
0 1 2 3 4 5
- Random value:
r = 2
total
is now4
2
is not in themap
, thusx = 2
- Update
map
withmap[6] = 5
andmap[2] = 4
- Chosen values:
{6, 2}
- Remaining numbers:
-
The randomly generated number has appeared before:
- Remaining numbers:
0 1 2 3 4
- Random value:
r = 2
, which repeats total
is now3
- Since
map[2] = 4
,x = 4
- Update
map
withmap[6] = 5
andmap[2] = 3
- Chosen values:
{6, 2, 4}
- Remaining numbers: