[BFS] 백준: 단지번호붙이기(Swift)

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

난이도: 실버1

사용 언어: Swift

카테고리: BFS

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

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 map = [[Int]]()
var countArr = [Int]()

for _ in 0..<n {
  let input = readLine()!
  let l = Array(input).map { Int(String($0))! }
  map.append(l)
}

func bfs(start: (y: Int, x: Int)) -> Int {
  let lrud: [(y: Int, x: Int)] = [
    (0,-1),
    (0,1),
    (-1,0),
    (1,0)
  ]
  var count = 1
  var queue = Queue<(y: Int, x: Int)>()
  queue.inQueue(element: start)
  let (y,x) = start
  map[y][x] = 0
  
  while !queue.isEmpty {
    let p = queue.deQueue()
    
    for i in 0..<4 {
      let next = (p.y + lrud[i].y, p.x + lrud[i].x)
      if (0..<n).contains(next.0) && (0..<n).contains(next.1) {
        if map[next.0][next.1] == 1 {
          map[next.0][next.1] = 0
          count += 1
          queue.inQueue(element: next)
        }
      }
    }
  }
  return count
}


for y in 0..<n {
  for x in 0..<n {
    if map[y][x] == 1 {
      let result = bfs(start: (y,x))
      countArr.append(result)
    }
  }
}

print(countArr.count)
countArr.sorted(by: <)
  .forEach {
  print($0)
}

 

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

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

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

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Esiwon
[BFS] 백준: 단지번호붙이기(Swift)
상단으로

티스토리툴바