1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] need help in python algorithm, problem with variable?

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    i am trying to solve a python algorithm problem but having trouble i will explain the question below ( I couldn't copy it here)

    Q : in a N*N array, each square consisting of random numbers, (every number is different)

    You are at a random number, you need to move to a neighboring number that is smaller than you. You can only move in 4 directions(up, down, left, right). When you move, if there are more than one place you can move to, you should only move to the smallest number possible.

    example: 19 57 74 73 94

    26 27 32 98 61

    40 88 49 38 25

    21 66 53 95 46

    80 23 58 39 89

    if you start at 49, you move like this: 49 -> 32 -> 27 -> 26 -> 19, so you move 4 times.

    Keep moving until you cannot move anymore. Return the maximal times you can move in each test case.

    my code:

    import sys
    sys.stdin = open('input.txt', 'r')

    T = int(input())
    for test_case in range(1, T + 1):

    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]

    # directions
    di = [-1, 1, 0, 0]
    dj = [0, 0, -1, 1]

    # max move
    # max(count_list)

    count_list = []
    count = 0 # count every time you move
    for i in range(N):
    for j in range(N):
    for d in range(4):
    ni = i + di[d]
    nj = j + dj[d]
    small_list_arr = [] # smallest of arr[ni][nj]
    if 0 <= ni < N and 0 <= nj < N: # inside N*N
    if arr[ni][nj] < arr[j]: # if there is smaller neighboring num
    small_list_arr.append(arr[ni][nj])
    # if there are multiple smaller neighboring nums
    if arr[ni][nj] == min(small_list_arr):
    count += 1 # move count
    ni, i = i, ni # new i, j
    nj, j = j, nj

    count_list.append(count)
    print(f'#{test_case} {max(count_list)}')


    my problem is, I think I am okay with finding the new (i, j) (smallest neighboring number's location) but when I use the debugger I find that <for d in range(4)> does not start over from 0 again, for example if I found new (i, j) when d = 2, the debugger shows that when you go back up to <for d in range(4)> the d starts from 2. how do i solve this? maybe there is a problem with how i allocate ni, nj to i, j variables?

    I tried break but didn't work, I am new to python so need help sorry for my english

    Continue reading...

Compartilhe esta Página