// 开心消消乐
var m = 0 // 行
var n = 0 // 列
var strings: [[String]] = []
func HW2023017() {
// 测试用例
// let nums = "3 3"
// strings = [["1","0","1"], ["0","1","0"], ["1","0","1"]]
// let nums = "4 4"
// strings = [["1","1","0","0"], ["0","0","0","1"], ["0","0","1","1"], ["1","1","1","1"]]
// 开始代码
let nums = String(readLine()!)
let numsArr = nums.components(separatedBy: " ").map { Int($0) ?? 0}
while let line = readLine() {
let num = line.components(separatedBy: " ")
if num.count > 0 {
strings.append(num)
}
}
n = Int(numsArr.first!)
m = Int(numsArr.last!)
var res = 0
for i in 0..<n {
for j in 0..<m {
if strings[i][j] == "1" {
strings[i][j] = "0"
// 回溯法处理数据更换问题
handleOnePadding(i, j)
res += 1
}
}
}
print(res)
}
func handleOnePadding(_ x: Int, _ y: Int) {
if x > 0 {
if strings[x-1][y] == "1" { // 上
strings[x-1][y] = "0"
handleOnePadding(x-1, y)
}
if y > 0 && strings[x-1][y-1] == "1" { // 左上
strings[x-1][y-1] = "0"
handleOnePadding(x-1, y-1)
}
if y < m-1 && strings[x-1][y+1] == "1" { // 右上
strings[x-1][y+1] = "0"
handleOnePadding(x-1, y+1)
}
}
if x < n-1 {
if strings[x+1][y] == "1" { // 下
strings[x+1][y] = "0"
handleOnePadding(x+1, y)
}
if y > 0 && strings[x+1][y-1] == "1" { // 左下
strings[x+1][y-1] = "0"
handleOnePadding(x+1, y-1)
}
if y < m-1 && strings[x+1][y+1] == "1" { // 右下
strings[x+1][y+1] = "0"
handleOnePadding(x+1, y+1)
}
}
if y > 0 && strings[x][y-1] == "1" { // 左
strings[x][y-1] = "0"
handleOnePadding(x, y-1)
}
if y < m-1 && strings[x][y+1] == "1" { // 右
strings[x][y+1] = "0"
handleOnePadding(x, y+1)
}
}
网友评论