You are given a board with N row and M columns. We will use (i,j) to denote the j-th cell in the i-th row (0-based indices). Each cell is initially white. You goal is to have a board that has at least one black cell in each row, and at the same time at least one black cell in each column.
You will paint the cells black in turns. In each turn, you select one cell (in a specific way that is given below) and color it black. You stop as soon as your goal is achieved.
You are given a
Formally, let s be the sum of all p[i][j]. Then in each turn the cell (i,j) is chosen with probability p[i][j]/s. Note that the same cell may be chosen multiple times: we may sometimes choose a cell that is already black.
The constraints guarantee that achieving your goal is possible. Return the expected number of turns until your goal is achieved.
This board is symmetric, so we can just assume that the cell (0,0) was chosen in the first turn.
Then there will be some additional turns until some other cell is chosen for the first time. The probability of choosing a different cell is 3/4, thus the expected number of these additional turns is 4/3.
Now, what is the second cell to be colored black?
Thus the answer is 1 + 4/3 + (2/3 * 2) = 11/3.
Each of the cells (0,0) and (1,1) has probability 1/2 to be chosen in each turn. One of those cells will be colored black in the first turn.
Then there will be some additional turns until the other cell is chosen. As that happens with probability 1/2, the expected number of additional turns is 2.
Thus the total expected number of turns is 1+2 = 3.