Untitled
unknown
python
a year ago
1.1 kB
2
Indexable
Never
matrix = [] with open('input.txt', 'r') as file: for line in file: buff_list = [int(string)for string in line.split()] matrix.append(buff_list) def dfs(grid, i, j, num): if i<0 or j<0 or j>= len(grid[0]) or i>= len(grid) or grid[i][j]==0: return grid[i][j]=num dfs(grid, i, j+1, num) dfs(grid, i+1, j, num) dfs(grid, i-1, j, num) dfs(grid, i, j-1, num) def numIslands(grid): if not grid: return 0 res = 0 num=1 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] != 0: dfs(grid, i, j, num) res+=1 num+=1 return res, grid res, grid = numIslands(matrix) with open('output.txt', 'w') as file: file.write(str(res)) file.write('\n') for ind, element in enumerate(grid): string = [str(number) for number in element] file.write(' '.join(string)) if ind != len(grid) - 1: file.write('\n')