Respuesta :
Answer: (This is python)
def read_matrix(file_name):
matrix = []
with open(file_name, 'r') as file:
rows, cols = map(int, file.readline().split())
for _ in range(rows):
matrix.append(list(map(int, file.readline().split())))
return matrix
def is_valid_move(matrix, visited, row, col):
rows = len(matrix)
cols = len(matrix[0])
return 0 <= row < rows and 0 <= col < cols and not visited[row][col] and matrix[row][col] > 0
def find_path(matrix, visited, row, col, path):
if row == len(matrix) - 1 and col == len(matrix[0]) - 1:
return True
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if is_valid_move(matrix, visited, new_row, new_col):
visited[new_row][new_col] = True
path.append((new_row, new_col))
if find_path(matrix, visited, new_row, new_col, path):
return True
path.pop()
visited[new_row][new_col] = False
return False
def print_path(path, matrix):
for row, col in path:
print(matrix[row][col], end=" ")
print()
def main():
file_name = input("Enter the file name: ")
matrix = read_matrix(file_name)
rows = len(matrix)
cols = len(matrix[0])
visited = [[False for _ in range(cols)] for _ in range(rows)]
visited[0][0] = True
path = [(0, 0)]
if find_path(matrix, visited, 0, 0, path):
print("Path with positive sum:")
print_path(path, matrix)
else:
print("No path with positive sum found")
if __name__ == "__main__":
main()
Explanation:
This program first reads the matrix from the file provided by the user, then it finds a path from the top-left to the bottom-right, adhering to the specified conditions. Finally, it prints the path with a positive sum if such a path exists.