iOS Swift
import Foundation
/**
m行, n列
10,10
0,0,0,0,0,0,0,0,0,0
0,0,0,1,1,0,1,0,0,0
0,1,0,0,0,0,0,1,0,1
1,0,0,0,0,0,0,0,1,1
0,0,0,1,1,1,0,0,0,1
0,0,0,0,0,0,1,0,1,1
0,1,1,0,0,0,0,0,0,0
0,0,0,1,0,1,0,0,0,0
0,0,1,0,0,1,0,0,0,0
0,1,0,0,0,0,0,0,0,0
6,8
*/
class Node {
let value: Int
var check: Bool = false
init(_ value: Int) {
self.value = value
}
}
let first = readLine()!.split(separator: ",")
let (m, n) = (Int(first[0])!, Int(first[1])!)
var teamCount = 0
var count = 0
var maxCount = 0
var dict: [String: Node] = [:];
for row in 0..<m {
let line = readLine()!.split(separator: ",").map{ Int($0) }.compactMap { $0 }
for column in 0..<n {
let location = "\(row)\(column)"
dict[location] = Node(line[column])
}
}
func traverse(node: Node, row: Int, column: Int) {
count += 1
node.check = true
if column != 0, row != 0, let topleft = dict["\(row - 1)\(column - 1)"], topleft.value == 1, !topleft.check {
traverse(node: topleft, row: row - 1, column: column - 1)
}
if row != 0, let top = dict["\(row - 1)\(column)"], top.value == 1, !top.check {
traverse(node: top, row: row - 1, column: column)
}
if row != 0, column != n - 1, let topright = dict["\(row - 1)\(column + 1)"], topright.value == 1, !topright.check {
traverse(node: topright, row: row - 1, column: column + 1)
}
if column != 0, let left = dict["\(row)\(column - 1)"], left.value == 1, !left.check {
traverse(node: left, row: row, column: column - 1)
}
if column != n - 1, let right = dict["\(row)\(column + 1)"], right.value == 1, !right.check {
traverse(node: right, row: row, column: column + 1)
}
if row != m - 1, column != 0, let buttomleft = dict["\(row + 1)\(column - 1)"], buttomleft.value == 1, !buttomleft.check {
traverse(node: buttomleft, row: row + 1, column: column - 1)
}
if row != m - 1, let buttom = dict["\(row + 1)\(column)"], buttom.value == 1, !buttom.check {
traverse(node: buttom, row: row + 1, column: column)
}
if row != m - 1, column != 0, let buttomright = dict["\(row + 1)\(column + 1)"], buttomright.value == 1, !buttomright.check {
traverse(node: buttomright, row: row + 1, column: column + 1)
}
}
for row in 0..<m {
for column in 0..<n {
let location = "\(row)\(column)"
guard let node = dict[location], node.value == 1, !node.check else { continue }
teamCount += 1
maxCount = count > maxCount ? count : maxCount
count = 0
traverse(node: node, row: row, column: column)
}
}
maxCount = count > maxCount ? count : maxCount
print(teamCount, maxCount)