[BFS] 백준: 안전 영역(Swift)

2022. 11. 1. 17:50·코테

난이도: 실버 1

사용 언어: Swift

카테고리: BFS

https://www.acmicpc.net/problem/2468

 

 

2468번: 안전 영역

재난방재청에서는 많은 비가 내리는 장마철에 대비해서 다음과 같은 일을 계획하고 있다. 먼저 어떤 지역의 높이 정보를 파악한다. 그 다음에 그 지역에 많은 비가 내렸을 때 물에 잠기지 않는

www.acmicpc.net

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
'코테' 카테고리의 다른 글
  • [DFS] 백준 11725번: 트리의 부모 찾기(Swift)
  • [DFS] 백준 1987번: 알파벳(Swift)
  • [BFS] 백준: 적록색약(Swift)
  • [BFS] 백준: 섬의 개수(Swift)
Esiwon
Esiwon
iOS 개발 블로그
  • Esiwon
    시원한 코드 기록
    Esiwon
  • 전체
    오늘
    어제
    • 분류 전체보기 (70)
      • iOS&Swift (24)
      • git & github (1)
      • 코테 (41)
      • 네부캠 회고 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    브루트포스 알고리즘
    photoUI
    재귀
    백준
    회고
    네부캠
    dfs
    코테
    ios
    노드
    비동기
    GCD
    알고리즘
    Combine
    탐색
    구현
    실버
    PhotoKit
    다이나믹 프로그래밍
    그리디
    Swift
    Race Condition
    이분탐색
    완전탐색
    챌린지
    동시성
    코딩테스트
    photos
    BFS
    Property wrapper
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Esiwon
[BFS] 백준: 안전 영역(Swift)
상단으로

티스토리툴바