使用Python处理二维数组:将单元格数≥5的同值区域置0
Absolutely, this is a classic connected components labeling task—there's a straightforward algorithm to solve this problem using either BFS (Breadth-First Search) or DFS (Depth-First Search) to identify large same-value regions, then modify them accordingly. Let me break it down for you:
Step 1: Core Approach
The solution has three key stages:
- Identify connected regions: Traverse the grid to find all groups of adjacent cells (4-directional: up, down, left, right, which matches your example results) with the same non-zero value.
- Filter large regions: Check if a region has 5 or more cells.
- Modify the grid: Set all cells in qualifying large regions to 0.
Step 2: Implementation Walkthrough (Pseudocode)
Here's a clear, actionable pseudocode using BFS (easy to translate to most programming languages like Python, JavaScript, etc.):
# Initialize the original grid and a visited matrix to track processed cells original_grid = [[1,1,1,2,2], [1,1,2,3,2], [2,2,2,3,1], [2,1,0,3,2], [2,0,3,3,0]] rows = length of original_grid cols = length of original_grid[0] visited = 2D array filled with False (same size as original_grid) # Traverse every cell in the grid for each row index i from 0 to rows-1: for each column index j from 0 to cols-1: # Only process unvisited, non-zero cells if not visited[i][j] and original_grid[i][j] != 0: current_value = original_grid[i][j] queue = initialize a queue with (i, j) visited[i][j] = True component_cells = list containing (i, j) # BFS to collect all connected cells with the same value while queue is not empty: x, y = dequeue from queue # Check all 4-directional neighbors for each direction in [(-1,0), (1,0), (0,-1), (0,1)]: nx = x + direction[0] ny = y + direction[1] # Ensure neighbor is within grid bounds if 0 <= nx < rows and 0 <= ny < cols: if not visited[nx][ny] and original_grid[nx][ny] == current_value: visited[nx][ny] = True enqueue (nx, ny) to queue add (nx, ny) to component_cells # If region size meets the threshold, set all cells to 0 if length of component_cells >= 5: for each (x, y) in component_cells: original_grid[x][y] = 0 # The original_grid now holds your desired output print(original_grid)
Step 3: Key Notes
- 4 vs 8 Connectivity: The pseudocode uses 4-directional adjacency (up/down/left/right), which aligns with your sample result. If you ever need to include diagonal neighbors, just update the direction list to include
(-1,-1), (-1,1), (1,-1), (1,1). - Handling Zero Values: We skip zero cells in the initial traversal because your sample leaves existing zeros unchanged—you can adjust this if needed for different use cases.
- Efficiency: This approach runs in O(rows * cols) time, since each cell is visited exactly once, making it efficient even for larger grids.
内容的提问来源于stack exchange,提问作者Brian Barbieri
相关产品推荐
相关产品推荐

