Search code examples
cmatrixdiagonal

How to check if there are multiple 1s in any diagonal of matrix?


So I have task where I have to check if there are multiple 1s on any diagonal of a 8x8 matrix.

For example if this is the matrix:

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

Output should be "No", because there isn't a diagonal with multiple 1s.

But for this:

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

output should be "Yes" since it has two number 1 in one diagonal. I can't quite figure out how to make it check diagonal.


Solution

  • For searching all the diagonals in a matrix you just need to check the difference of the indexes in a for loop for example.

    Let's assume i is the index for each element in a row, and j the index for each column of the element

    Consider now a matrix 4x4:

    [0,0,0,1]
    [0,0,1,0]
    [0,1,0,0]
    [1,0,0,0]
    

    To access each diagonal of this matrix you need to check what is the value for i-j.

    Let's build a matrix with the value of i - j for each element:

    [ 0, 1, 2, 3]
    [-1, 0, 1, 2]
    [-2,-1, 0, 1]
    [-3,-2,-1, 0]
    

    Now is really easy to see that all we need to do to iterate the diagonals is check the i-j value -> if it's the same value, the element belongs to the same diagonal.

    To check the other diagonals just compute i + j :

    [ 0, 1, 2, 3]
    [ 1, 2, 3, 4]
    [ 2, 3, 4, 5]
    [ 3, 4, 5, 6]