Search for a position with the same number in the row and column

For a two-dimensional array of equal dimensions (ie nxn) containing only 0 and 1, how can I find (ignoring the matrix [i] [i]) the i-th row that has all 0 and the i-th column that has all 1. If such a self does not exist, then return -1.

matrix [i] [i] can have anything.

Expected time complexity: O (n)

for example

for a given 4 × 4 matrix

1 1 0 0
0 1 0 0
1 1 0 1
0 1 0 0

the answer is 1 (i is based on zero), because the 2nd row has all 0, and the second column has all 1 (the value in [1, 1] is ignored).

+4
source share
3 answers

First of all, such a matrix will have only 1 or 0 answers.

  • Start walking on the first line until you find 1 (diagonal values ​​should be ignored).
  • , 0. , 1.
  • 1, .

, i, , . -1.

1 1 n + n, 1 , n + n , 4 * n , O (n).

:

0 0 0 1 S S S S S S
S S S 1 S S S S S S
S S S 0 0 0 1 S S S
S S S S S S 1 S S S
S S S S S S 1 S S S
S S S S S S 1 S S S
S S S S S S 1 0 0 0 X
S S S S S S S S S S
S S S S S S S S S S
S S S S S S S S S S

7.

+4

:

all-ones ( ), 1 , .

, , all-ones.

.

0

Decision:

return -1

Because if some row has all zeros, and in some column everything is all that will be in the cell, where do they intersect?

-3
source

Source: https://habr.com/ru/post/1617749/


All Articles