요구능력 : BFS
코드설명 :
후기 : 기초적인 BFS문제인것 같다.
아기상어보다 아기상어2 난이도가 훨씬낮다.
let nm = readLine()!.split(separator: " ").map{Int(String($0))!}
let n = nm[0]
let m = nm[1]
var arr = [[Int]]()
let dx = [-1, 1, 0, 0, -1, 1, 1, -1]
let dy = [0, 0, -1, 1, 1, -1, 1, -1]
for _ in 0..<n{
arr.append(readLine()!.split(separator: " ").map{Int(String($0))!})
}
var result = [Int]()
func bfs(_ startX: Int, _ startY: Int){
var visited = Array(repeating: Array(repeating: false, count: 251), count: 251)
var queue = [((Int, Int), Int)]() //x, y, 안전거리
queue.append(((startX, startY), 0))
visited[startX][startY] = true
var idx = 0
while queue.count > idx {
let pop = queue[idx]
let x = pop.0.0
let y = pop.0.1
let safeDistance = pop.1
idx += 1
if arr[x][y] == 1 {
result.append(safeDistance)
break
}
for i in 0..<8{
let nx = x + dx[i]
let ny = y + dy[i]
if nx < 0 || nx >= n || ny < 0 || ny >= m || visited[nx][ny] {continue}
queue.append(((nx, ny), safeDistance + 1))
visited[nx][ny] = true
}
}
}
for i in 0..<n {
for j in 0..<m{
if arr[i][j] == 1 {continue}
bfs(i, j)
}
}
print(result.max()!)
'Algorithm > 문제풀이_백준' 카테고리의 다른 글
[Swift][BFS] 백준 2234번 (성곽) (0) | 2022.02.03 |
---|---|
[Swift][BFS][시간초과] 백준 4991번 (로봇 청소기) (0) | 2022.02.03 |
[Swift][BFS] 백준 5014번 (스타트링크) (0) | 2022.01.27 |
[Swift][BFS] 백준 14395번 (4연산) (0) | 2022.01.27 |
[Swift][BFS] 백준 10026 (적록색약) (0) | 2022.01.25 |
댓글