99 lines
2.8 KiB
Swift
99 lines
2.8 KiB
Swift
func solve() {
|
|
guard let input1 = readLine() else { return }
|
|
let NM = input1.split(separator: " ").compactMap{Int($0)}
|
|
guard NM.count == 2 else { return }
|
|
let N = NM[0], M = NM[1]
|
|
|
|
var field: [[Int]] = []
|
|
for i in 0..<N {
|
|
guard let input2 = readLine() else { return }
|
|
let row = input2.compactMap{Int(String($0))}
|
|
field.append(row)
|
|
for j in 0..<M {
|
|
if field[i][j] == 1 {
|
|
field[i][j] = -1
|
|
}
|
|
}
|
|
}
|
|
|
|
var groupSize: [Int] = []
|
|
|
|
func BFS(group n: Int, col x: Int, row y: Int) {
|
|
var qu: [(Int, Int)] = [(x, y)]
|
|
var front = 0
|
|
field[y][x] = n
|
|
var cnt = 1
|
|
|
|
while front < qu.count {
|
|
let (cx, cy) = qu[front]
|
|
front += 1
|
|
|
|
for (nx, ny) in [(cx+1, cy), (cx-1, cy), (cx, cy+1), (cx, cy-1)] {
|
|
if 0 <= nx && nx < M && 0 <= ny && ny < N && field[ny][nx] == 0 {
|
|
qu.append((nx, ny))
|
|
field[ny][nx] = n
|
|
cnt += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
groupSize.append(cnt)
|
|
}
|
|
|
|
var group = 1
|
|
for row in 0..<N {
|
|
for col in 0..<M {
|
|
if field[row][col] == 0 {
|
|
BFS(group: group, col: col, row: row)
|
|
group += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
var ans: [[Int]] = Array(repeating: Array(repeating: 0, count: M), count: N)
|
|
for row in 0..<N {
|
|
for col in 0..<M {
|
|
if field[row][col] != -1 {
|
|
continue
|
|
}
|
|
|
|
var nearbyGroup: [Int] = []
|
|
var cnt = 1
|
|
|
|
for (nc, nr) in [(col+1, row), (col-1, row), (col, row+1), (col, row-1)] {
|
|
if 0 <= nc && nc < M && 0 <= nr && nr < N && field[nr][nc] != -1 {
|
|
let nowGroup = field[nr][nc]
|
|
|
|
if nearbyGroup.isEmpty {
|
|
nearbyGroup.append(nowGroup)
|
|
cnt += groupSize[nowGroup-1]
|
|
}
|
|
|
|
else {
|
|
|
|
var grooupCheck = true
|
|
for g in nearbyGroup {
|
|
if g == nowGroup {
|
|
grooupCheck = false
|
|
}
|
|
}
|
|
|
|
if grooupCheck {
|
|
nearbyGroup.append(nowGroup)
|
|
cnt += groupSize[nowGroup-1]
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
ans[row][col] = cnt%10
|
|
}
|
|
}
|
|
|
|
for row in ans {
|
|
print(row.compactMap({String($0)}).joined(separator: ""))
|
|
}
|
|
}
|
|
|
|
solve()
|