业务场景:
有个二维矩阵 513 * 513 ,取值只有 0 或 1 ,根据值绘图,0 白色 1 黑色。
现在需要把不规则的黑色绘制成矩形,如下图:
代码如下:
func findConnectedRegion(matrix: [[Int]]) -> [[(Int, Int)]] {
var result: [[(Int, Int)]] = []
// var visited: Set<(Int, Int)> = []
var visited: Set<String> = []
let numRows = matrix.count
let numCols = matrix[0].count
for i in 0..<matrix.count {
for j in 0..<matrix[0].count {
let position = (i, j)
let str = String(i)+"-"+String(j)
if matrix[i][j] == 1 && !visited.contains(str) {
var region: [(Int, Int)] = []
dfs(matrix: matrix, rows: numRows,cols: numCols,position: position, visited: visited, region: ®ion)
result.append(region)
}
}
}
return result
}
func dfs(matrix: [[Int]],rows:Int,cols:Int,position: (Int, Int), visited: Set<String>, region: inout [(Int, Int)]) {
// let numRows = matrix.count
// let numCols = matrix[0].count
let numRows = rows
let numCols = cols
let (row, col) = position
self.str = String(position.0)+"-"+String(position.1)
// Check if the current position is within bounds and is part of the region
guard row >= 0, row < numRows, col >= 0, col < numCols, matrix[row][col] == 1, !visited.contains(str) else {
return
}
self.visited.insert(str)
region.append(position)
// Explore neighbors in all four directions
dfs(matrix: matrix,rows: numRows,cols: numCols, position: (row - 1, col), visited: visited, region: ®ion) // Up
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row + 1, col), visited: visited, region: ®ion) // Down
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col - 1), visited: visited, region: ®ion) // Left
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col + 1), visited: visited, region: ®ion) // Right
}
好几处局部变量改成了属性,但还是不同位置报相同的错:Thread 1: EXC_BAD_ACCESS (code=2, address=0x16b6a7fc0)
完全不知道问题出在哪了,请大佬指点
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.