Learn Python from a baby! Record the questions in the Blue Bridge Cup Python learning and test preparation process, and record every moment.
Attached is a summary post: Pupils Blue Bridge Cup Python Breakthrough | Summary_COCOgsta's Blog-CSDN Blog
【Description】
There is a sea area divided into N * M squares, some of which are polluted (indicated by 0), and some sea areas are not polluted (indicated by 1).
May I ask how many unpolluted independent sea areas are in this N * M sea area (unpolluted independent sea area means that the sea area is surrounded by polluted sea areas up, down, left, and right, and the sea areas other than N * M are all polluted) polluted seas)
For example: N=4, M=5, in the sea area of 4 * 5, the polluted sea area and the unpolluted sea area are as follows:
In this 4 * 5 sea area, 3 sea areas (green) are not polluted, because each block is surrounded by polluted sea areas.
【Enter description】
Input two positive integers N and M in the first line, N represents the row of the matrix grid, M represents the column of the matrix grid, and N and M are separated by a comma;
The second line starts to input N lines, each line has M numbers (numbers can only be 1 or 0, 1 means unpolluted sea area, 0 means polluted sea area)
【Output description】
Output an integer, indicating how many of the N * M sea areas are independent sea areas that are not polluted
【Sample input】
4,5
1,1,0,0,0
1,0,1,0,0
1,0,0,0,0
1,1,0,1,1
【Sample output】
3
【Code Explanation】
N, M = [int(i) for i in input().split(",")]
ls = [[int(i) for i in input().split(',')] for i in range(N)]
v = [[0] * M for i in range(N)] #记录探索结果
def dfs(x, y):
v[x][y] = 1
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
xx = x + dx
yy = y + dy
if 0<=xx<N and 0<=yy<M and ls[xx][yy] == 1 and v[xx][yy] == 0:
dfs(xx, yy)
cnt = 0
for i in range(N):
for j in range(M):
if ls[i][j] == 1 and v[i][j] == 0:
dfs(i, j)
cnt += 1
print(cnt)
复制代码
【operation result】
4,5
1,1,0,0,0
1,0,1,0,0
1,0,0,0,0
1,1,0,1,1
3