记录一次不太愉快的code test 输入一个二维数组,只有0,1元素。问1围起来的面积
思路是找没有被1围起来的棋子,遍历四条边,如果是0,则与它相邻的元素0肯定没有被围起来(继续深度优先搜索到所有相邻的0,且改变其状态,免得下一个位置遍历的时候重复搜索)。然后求剩下的面积即可
class Solution:
def weiqi(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
def dfs(x, y):
if x<0 or x>=m or y<0 or y>=n or grid[x][y] == 1:
return 0
grid[x][y] = 1
return 1 + dfs(x-1,y) + dfs(x+1,y) + dfs(x, y-1) + dfs(x, y+1)
num_free = 0
for r in range(m):
if grid[r][0] == 0:
num_free += dfs(r, 0)
if grid[r][n-1] == 0:
num_free += dfs(r, n-1)
for c in range(n):
if grid[0][c] == 0:
num_free += dfs(0, c)
if grid[m-1][c] == 0:
num_free += dfs(m-1, c)
return m*n - num_free
输入
[[0,1,1,0,1], [1,0,0,1,1],[0,1,1,1,0],[0,0,1,0,0]]
输出
12