给我提供一个用python写的河水分割的代码
时间: 2024-05-10 09:21:33 浏览: 27
以下是一个简单的用python实现河水分割的代码:
```python
def riverSizes(matrix):
sizes = []
visited = [[False for value in row] for row in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if visited[i][j]:
continue
traverseNode(i, j, matrix, visited, sizes)
return sizes
def traverseNode(i, j, matrix, visited, sizes):
currentRiverSize = 0
nodesToExplore = [[i, j]]
while len(nodesToExplore):
currentNode = nodesToExplore.pop()
i = currentNode[0]
j = currentNode[1]
if visited[i][j]:
continue
visited[i][j] = True
if matrix[i][j] == 0:
continue
currentRiverSize += 1
unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited)
for neighbor in unvisitedNeighbors:
nodesToExplore.append(neighbor)
if currentRiverSize > 0:
sizes.append(currentRiverSize)
def getUnvisitedNeighbors(i, j, matrix, visited):
unvisitedNeighbors = []
if i > 0 and not visited[i - 1][j]:
unvisitedNeighbors.append([i - 1, j])
if i < len(matrix) - 1 and not visited[i + 1][j]:
unvisitedNeighbors.append([i + 1, j])
if j > 0 and not visited[i][j - 1]:
unvisitedNeighbors.append([i, j - 1])
if j < len(matrix[0]) - 1 and not visited[i][j + 1]:
unvisitedNeighbors.append([i, j + 1])
return unvisitedNeighbors
```
这个代码通过深度优先搜索遍历整个矩阵,对于每个遍历到的点,如果它是未访问过的河流,则从这个点开始继续搜索,直到搜索完整个河流,并记录河流大小,最终返回所有河流的大小。
相关推荐
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)