I recently solved the problem below from leetcode:
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). Find the maximum area of an island in the given 2D array.
This is how I normally write python code. I am thinking this might not be really Pythonic. Please help review the code.
from operator import add def max_area_of_island(grid): """ :type grid: List[List[int]] :rtype: int """ rlen = len(grid) clen = len(grid) visited = [ * clen for _ in range(rlen)] max_island = 0 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] def add_dir(cur_loc, d): cur_i, cur_j = cur_loc new_i, new_j = tuple(map(add, cur_loc, d)) if new_i >= 0 and new_i < rlen and new_j >= 0 and new_j < clen: #print("all good") return new_i, new_j #print("error") return -1, -1 max_area = 0 for i in range(rlen): for j in range(clen): if grid[i][j] == 0 or visited[i][j]: continue area = 1 q = [(i,j)] visited[i][j] = True #print("before qsize", q.qsize()) while q: #print("during qsize", q.qsize()) cur = q.pop() for _,d in enumerate(dirs): new_i, new_j = add_dir(cur, d) if new_i < 0 or visited[new_i][new_j]: continue if new_i >= 0 and grid[new_i][new_j]: new_loc = (new_i, new_j) q.append(new_loc) visited[new_i][new_j] = True area += 1 max_area = max(area, max_area) return max_area