import Foundation
let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
let n = input[0], m = input[1]
var matrix: [[Int]] = []
var answer: [[Int]] = []
var visited: [[Bool]] = Array(repeating: Array(repeating: false, count: m), count: n)
(0..<n).forEach { _ in
let row = readLine()!.split(separator: " ").map{ Int(String($0))! }
matrix.append(row)
}
var start: (y:Int, x: Int) = (y: 0, x: 0)
for (i, row) in matrix.enumerated() {
var aRow: [Int] = []
for (j, d) in row.enumerated() {
if d == 0 {
aRow.append(0)
} else if d == 1 {
aRow.append(-1)
} else {
start = (y: i, x: j)
aRow.append(0)
}
}
answer.append(aRow)
}
func bfs(sy: Int, sx: Int) {
var queue: [(y: Int, x: Int)] = [(sy,sx)]
let dy = [0, 0, 1, -1]
let dx = [1, -1, 0, 0]
while !queue.isEmpty {
let (y,x) = queue.removeFirst()
(0..<4).forEach { i in
let ny = dy[i] + y
let nx = dx[i] + x
if ny >= 0 && ny < n && nx >= 0 && nx < m && !visited[ny][nx] {
if matrix[ny][nx] == 0 {
answer[ny][nx] = 0
return
}
answer[ny][nx] = answer[y][x] + 1
visited[ny][nx] = true
queue.append((ny, nx))
}
}
}
}
visited[start.y][start.x] = true
bfs(sy: start.y, sx: start.x)
answer.forEach {
print($0.map{ String($0) }.joined(separator: " "))
}
참고 : https://www.acmicpc.net/problem/14940