[BFS] 백준: 적록색약(Swift)

2022. 10. 29. 00:54·코테

난이도: 골드 5

사용 언어: Swift

카테고리: BFS

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

10026번: 적록색약

적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)

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 map = [[Character]]()
var rbMap = [[Character]]()
for _ in 0..<n {
  let y = Array(readLine()!)
  map.append(y)
  rbMap.append(y.map { $0 == "G" ? "R" : $0 })
}

func bfs(start: (y: Int, x: Int), target: Character) -> Int {
  map[start.y][start.x] = "X"
  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)
  ]
  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..<n).contains(nextPoint.y)
          && (0..<n).contains(nextPoint.x)
          && map[nextPoint.y][nextPoint.x] == target {
        map[nextPoint.y][nextPoint.x] = "X"
        q.inQueue(element: nextPoint)
      }
    }
  }
  return 1
}

var r1 = 0
var r2 = 0
for y in 0..<n {
  for x in 0..<n {
    if map[y][x] != "X" {
      r1 += bfs(start: (y, x), target: map[y][x])
    }
  }
}

map = rbMap
for y in 0..<n {
  for x in 0..<n {
    if map[y][x] != "X" {
      r2 += bfs(start: (y, x), target: map[y][x])
    }
  }
}
print("\(r1) \(r2)")

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

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

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

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Esiwon
[BFS] 백준: 적록색약(Swift)
상단으로

티스토리툴바