Sarah111-AHM / Semsmah

2 stars 0 forks source link

show a path from top left to bottom right. In the matrix #6

Closed Sarah111-AHM closed 1 year ago

Sarah111-AHM commented 1 year ago

import numpy as np
rows, cols = np.where(matrix == 0)
if (0 in rows) and (len(rows)-1 in rows) and (0 in cols) and (len(cols)-1 in cols):
path_matrix = np.zeros_like(matrix)
path_matrix[rows, cols] = 1
path_indices = np.transpose(np.nonzero(path_matrix))
blocked_indices = np.transpose(np.nonzero(matrix == -1))
distances = np.zeros((len(path_indices), len(blocked_indices)))
        for i, path_index in enumerate(path_indices):
            for j, blocked_index in enumerate(blocked_indices):
                distances[i, j] = np.linalg.norm(path_index - blocked_index)
for i in range(len(path_indices)):
            distances_to_blocked = np.min(distances[:, i])
            if distances_to_blocked <= np.sqrt(2):
            return None
            return path_indices.tolist()
    else:
        return None
matrix = np.array([[0, 0, 0, -1, 0],
                   [-1, 0, 0, -1, -1],
                   [0, 0, 0, -1, 0],
                   [-1, 0, -1, 0, -1],
                   [0, 0, -1, 0, 0]])
if path:
    print("Path found:")
    for cell in path:
        print(cell)
else:
    print("No path found.")

image image image image image