Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def find_lowest_valley(terrain):
- """
- Megkeresi a legalacsonyabb „völgyet” a 2D-s térképen.
- A térkép egy numerikus értékeket tartalmazó listák listája (pl. [[5,3,4],[6,2,7],[8,9,1]]).
- Völgynek tekintünk egy cellát, ha minden létező (fel, le, balra, jobbra) szomszédja magasabb nála.
- Visszatérési érték:
- - Ha van legalább egy völgy, akkor egy tuple (i, j, érték), ahol (i,j) a koordináta,
- és érték a cella magassága.
- - Ha nincs egyetlen völgy sem, akkor None.
- """
- if not terrain or not terrain[0]:
- return None
- rows = len(terrain)
- cols = len(terrain[0])
- directions = [(-1,0), (1,0), (0,-1), (0,1)]
- lowest_valley = None # Ebbe fogjuk menteni a (i, j, magasság) hármasokat
- lowest_value = None # A legalacsonyabb völgy magassága
- for i in range(rows):
- for j in range(cols):
- current = terrain[i][j]
- is_valley = True # Kezdetben feltételezzük, hogy völgy
- for di, dj in directions:
- ni = i + di
- nj = j + dj
- if 0 <= ni < rows and 0 <= nj < cols:
- if terrain[ni][nj] <= current:
- is_valley = False
- break
- if is_valley:
- if lowest_valley is None or current < lowest_value:
- lowest_valley = (i, j, current)
- lowest_value = current
- return lowest_valley
- # ------------------------------------------------------------------------------------
- import numpy as np
- from typing import NamedTuple, Optional
- class Valley(NamedTuple):
- row: int
- col: int
- elevation: float
- def find_lowest_valley(terrain: np.ndarray) -> Optional[Valley]:
- """
- Megkeresi a legalacsonyabb völgyet egy 2D-s NumPy-tömbben.
- Völgy: a cella értéke szigorúan kisebb a négyirányú szomszédainál.
- """
- arr = np.asarray(terrain, dtype=float)
- if arr.ndim != 2:
- raise ValueError(f"A bemenetnek kétdimenziós tömbnek kell lennie (ndim={arr.ndim}).")
- rows, cols = arr.shape
- if rows == 0 or cols == 0:
- raise ValueError("A tömb nem lehet üres (legalább 1×1).")
- padded = np.pad(arr, pad_width=1, mode='constant', constant_values=np.inf)
- up = padded[0:rows, 1:cols+1]
- down = padded[2:rows+2, 1:cols+1]
- left = padded[1:rows+1, 0:cols]
- right = padded[1:rows+1, 2:cols+2]
- mask = (arr < up) & (arr < down) & (arr < left) & (arr < right)
- if not np.any(mask):
- return None
- min_elev = float(np.min(arr[mask]))
- coords = np.argwhere(mask & (arr == min_elev))
- i_min, j_min = coords[0]
- return Valley(row=i_min, col=j_min, elevation=min_elev)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement