난이도: 실버 1
Code
struct Queue<T> {
var memory = [T]()
var index = 0
var isEmpty: Bool {
memory.count < index + 1
}
mutating func inQueue(element: T) {
memory.append(element)
}
mutating func deQueue() -> T {
let v = memory[index]
index += 1
return v
}
}
let n = Int(readLine()!)!
var mapS = [[Int]]()
var max: Int = 0
var visitedS: [[Bool]] = Array(repeating: Array(repeating: false, count: n), count: n)
for _ in 0..<n {
let y = readLine()!.split(separator: " ").map { Int($0)! }
max = max > y.max()! ? max : y.max()!
mapS.append(y)
}
func bfs(start: (y: Int, x: Int), target: Int) {
count += 1
var q = Queue<(y: Int, x: Int)>()
q.inQueue(element: start)
visited[start.y][start.x] = true
let direction: [(y: Int, x: Int)] = [
(0,-1),
(0,1),
(-1,0),
(1,0)
]
while !q.isEmpty {
let currentP = q.deQueue()
for i in 0..<direction.count {
let nextP: (y: Int, x: Int) = (
currentP.y + direction[i].y,
currentP.x + direction[i].x
)
if (0..<n).contains(nextP.y)
&& (0..<n).contains(nextP.x)
&& visited[nextP.y][nextP.x] == false
&& map[nextP.y][nextP.x] > target {
visited[nextP.y][nextP.x] = true
q.inQueue(element: nextP)
}
}
}
}
var map = [[Int]]()
var visited = [[Bool]]()
var result = 0
var count = 0
for target in 0...max {
count = 0
map = mapS
visited = visitedS
for y in 0..<n {
for x in 0..<n {
if map[y][x] > target && visited[y][x] == false {
bfs(start: (y, x), target: target)
}
}
}
result = result > count ? result : count
}
print(result)
'코테' 카테고리의 다른 글
[DFS] 백준 11725번: 트리의 부모 찾기(Swift) (0) | 2022.11.07 |
---|---|
[DFS] 백준 1987번: 알파벳(Swift) (0) | 2022.11.02 |
[BFS] 백준: 적록색약(Swift) (0) | 2022.10.29 |
[BFS] 백준: 섬의 개수(Swift) (0) | 2022.10.27 |
[DFS]백준: 연결 요소의 개수(Swift) (0) | 2022.10.25 |