Alex Show
Alex Show

Reputation: 75

Horizontal and vertical neighbours of 2D array

I have 2 integers which tell the amount of rows and columns and 2 integers which define the position of an element. I need to find vertical and horizontal neighbours (diagonal should not be counted).

i.e input:

3, 3

1 2 3
4 5 6
7 8 9

1, 1

desired output:

2 4 6 8

I managed to create a brute force code which would manually process all corner cases like element[0][0] which have only 2 or 3 neighbours. Also I tried to add surrounding line to the matrix to remove corner cases but it seems to be even less time-efficient.

           z z z z z
1 2 3      z 1 2 3 z
4 5 6  ==> z 4 5 6 z
7 8 9      z 7 8 9 z
           z z z z z

Brute-force:

a = int(input())
b = int(input())
c = [list(map(int, input().split())) for i in range(a)]
d = int(input())
e = int(input())

z = []

if d == 0:
    if e == 0:
        z.append(c[d+1][e])
        z.append(c[d][e+1])
    elif e == b-1:
        z.append(c[d+1][e])
        z.append(c[d][e-1])
    else:
        z.append(c[d][e-1])
        z.append(c[d][e+1])
        z.append(c[d+1][e])
elif d == a-1:
    if e == 0:
        z.append(c[d][e+1])
        z.append(c[d-1][e])
    elif e == b-1:
        z.append(c[d][e-1])
        z.append(c[d-1][e])
    else:
        z.append(c[d-1][e])
        z.append(c[d][e+1])
        z.append(c[d][e-1])
else:
    z.append(c[d+1][e])
    z.append(c[d-1][e])
    z.append(c[d][e+1])
    z.append(c[d][e-1])

print(*z)

In code which adds an outter layers to matrix I just have the last part of appends left.

Please suggest an algorithm which would be more time-efficient. Thank you.

Upvotes: 0

Views: 611

Answers (2)

Alex Show
Alex Show

Reputation: 75

Thanks for all comments. Posting the code which passed time restrictions.

a = int(input())
b = int(input())
c = [list(map(int, input().split())) for i in range(a)]
d = int(input())
e = int(input())

x = (d, d, d-1, d+1)
y = (e-1, e+1, e, e)

z = sorted([c[i[0]][i[1]] for i in zip(x, y) if 0 <= i[0] <= a-1 and 0 <= i[1] <= b-1])

print(*z)

Upvotes: 1

Chandan Nayak
Chandan Nayak

Reputation: 13

In the example you mentioned, were you referring to the middle number or 5?

Accessing an element of an array is a constant time operation. In your case, let’s say you have to access neighbors of (i,j) element. So you just need to index for (i,j+1) (i, j-1) (i+1,j) and (I-1,j).

Upvotes: 0

Related Questions