简体   繁体   中英

How do I write O(n2) program of matrix n x n?

I am practicing and trying to write O(n^2) program that tests whether there are two 1s lying on the same row or the same column in A. Where A = nxn matrix of 0s and 1s.
Given A as:

n x n 矩阵

I should get answer return of 2 matches.
One is on the 1st row, and another on the 3rd column.

My 2nd Attempt:

def testLines():
    count = 0
    for x in range( 0, len(A)-1 ): 
        if( (A[x] == 1) & (A[x+1] == 1) ): 
        count+=1
    for y in range( 0, len(A)-1): 
        if( (A[y] == 1 & A[y+1]) == 1 ): 
        count+=1
    print( count, '1s has been matched in the array A')


testLines() 

You want to nest the two loops and change the indexes so that both x and y are parsed. Currently your code moves through (all x, y = 0) and (x = 0, all y).

A = [[0, 0, 1, 1],
     [0, 1, 0, 0],
     [0, 0, 1, 0],
     [0, 0, 1, 0]]

def testLines():
    count = 0
    N = len(A)
    for x in range(N): 
        for y in range(N):
            if A[x][y] == 1:
                if x+1 < N and A[x+1][y] == 1: 
                    count += 1
                if y+1 < N and A[x][y+1] == 1: 
                    count += 1
    print(count, '1s has been matched in the array A')

testLines() 

Alternatively, you can go the Schwarzenegger way and not check if (x+1, y) or (x, y+1) even exist. That will raise IndexError s that you can choose to ignore.

def testLines():
    count = 0
    N = len(A)
    for x in range(N): 
        for y in range(N):
            try:
                if A[x][y] == 1 and A[x+1][y] == 1 or A[x][y+1] == 1: 
                    count += 1
            except IndexError:
                continue
    print(count, '1s has been matched in the array A')

You can run one nested loop (n²) to get summation of rows. If summation is 2 then that row has two 1s.

Now interchange rows and columns(consider rows as columns & vice versa).

Again run nested loop (n²) to check summation of columns.

n²+n²= O(n²)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM