[BFS] 백준: 섬의 개수(Swift)

2022. 10. 27. 18:14·코테

난이도: 실버2

사용 언어: Swift

카테고리: BFS

 

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

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
  }
}



var results = [Int]()
while true {
  let wh = readLine()!.split(separator: " ").map { Int($0)! }
  let w = wh[0]
  let h = wh[1]
  
  if w == 0 && h == 0 { break }

  var map = [[Int]]()

  for _ in 0..<h {
    let y = readLine()!.split(separator: " ").map { Int($0)! }
    map.append(y)
  }

  var result = 0

  func bfs(start: (y: Int, x: Int)) {
    result += 1
    map[start.y][start.x] = 0
    var q = Queue<(y: Int, x: Int)>()
    q.inQueue(element: start)
    let direction: [(y: Int, x: Int)] = [
      (0,-1),
      (0,1),
      (-1,0),
      (1,0),
      (-1,-1),
      (-1,1),
      (1,-1),
      (1,1)
    ]
    while !q.isEmpty {
      let currentPoint: (y: Int, x: Int) = q.deQueue()
      
      for i in 0..<direction.count {
        let nextPoint: (y: Int, x: Int) = (currentPoint.y + direction[i].y, currentPoint.x + direction[i].x)
        if (0..<h).contains(nextPoint.y) && (0..<w).contains(nextPoint.x) && map[nextPoint.y][nextPoint.x] == 1 {
          map[nextPoint.y][nextPoint.x] = 0
          q.inQueue(element: nextPoint)
        }
      }
    }
  }

  for y in 0..<h {
    for x in 0..<w {
      if map[y][x] == 1 {
        bfs(start: (y, x))
      }
    }
  }
  results.append(result)
}

results.forEach { result in
  print(result)
}

'코테' 카테고리의 다른 글

[BFS] 백준: 안전 영역(Swift)  (0) 2022.11.01
[BFS] 백준: 적록색약(Swift)  (0) 2022.10.29
[DFS]백준: 연결 요소의 개수(Swift)  (0) 2022.10.25
[BFS] 백준: 유기농 배추(Swift)  (0) 2022.10.24
[DFS] 백준: 바이러스(Swift)  (0) 2022.10.20
'코테' 카테고리의 다른 글
  • [BFS] 백준: 안전 영역(Swift)
  • [BFS] 백준: 적록색약(Swift)
  • [DFS]백준: 연결 요소의 개수(Swift)
  • [BFS] 백준: 유기농 배추(Swift)
Esiwon
Esiwon
iOS 개발 블로그
  • Esiwon
    시원한 코드 기록
    Esiwon
  • 전체
    오늘
    어제
    • 분류 전체보기 (70)
      • iOS&Swift (24)
      • git & github (1)
      • 코테 (41)
      • 네부캠 회고 (4)
  • 블로그 메뉴

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

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Esiwon
[BFS] 백준: 섬의 개수(Swift)
상단으로

티스토리툴바