[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)
  • 블로그 메뉴

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

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바