-
[Swift] ๋ฐฑ์ค 10026 ์ ๋ก์์ฝ (Graph Traversal)๐ป Algorithm/Swift 2023. 1. 31. 22:49
๐ ํ์ด
๐ฌ Code
import Foundation let n = Int(readLine()!)! var graph = [[String]]() var visited = [[Bool]]() var cnt = [0, 0] let dx = [-1, 1, 0, 0] let dy = [0, 0, -1, 1] for _ in 0..<n { graph.append(readLine()!.map{ String($0) }) visited.append(Array<Bool>(repeating: false, count: n)) } func bfs(_ x: Int, _ y: Int, isRG: Bool) { var queue = [[x, y]] let color = graph[x][y] visited[x][y] = true while !queue.isEmpty { let now = queue.removeFirst() for i in 0..<4 { let nx = now[0] + dx[i] let ny = now[1] + dy[i] if 0..<n ~= nx && 0..<n ~= ny && !visited[nx][ny] { if isRG && (color == "R" || color == "G") && (graph[nx][ny] == "R" || graph[nx][ny] == "G") { queue.append([nx, ny]) visited[nx][ny] = true } else if graph[nx][ny] == color { queue.append([nx, ny]) visited[nx][ny] = true } } } } } for i in 0..<n { for j in 0..<n { if !visited[i][j] { bfs(i, j, isRG: false) cnt[0] += 1 } } } visited = Array.init(repeating: Array<Bool>(repeating: false, count: n), count: n) for i in 0..<n { for j in 0..<n { if !visited[i][j] { bfs(i, j, isRG: true) cnt[1] += 1 } } } print("\(cnt[0]) \(cnt[1])")
10026๋ฒ: ์ ๋ก์์ฝ
์ ๋ก์์ฝ์ ๋นจ๊ฐ์๊ณผ ์ด๋ก์์ ์ฐจ์ด๋ฅผ ๊ฑฐ์ ๋๋ผ์ง ๋ชปํ๋ค. ๋ฐ๋ผ์, ์ ๋ก์์ฝ์ธ ์ฌ๋์ด ๋ณด๋ ๊ทธ๋ฆผ์ ์๋ ์ฌ๋์ด ๋ณด๋ ๊ทธ๋ฆผ๊ณผ๋ ์ข ๋ค๋ฅผ ์ ์๋ค. ํฌ๊ธฐ๊ฐ NรN์ธ ๊ทธ๋ฆฌ๋์ ๊ฐ ์นธ์ R(๋นจ๊ฐ), G(์ด๋ก)
www.acmicpc.net
'๐ป Algorithm > Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๋ฐฑ์ค 1697 ์จ๋ฐ๊ผญ์ง (Graph Traversal) (0) 2023.02.12 [Swift] ๋ฐฑ์ค 15649 N๊ณผ M (1) (Back Tracking) (0) 2023.01.31 [Swift] ๋ฐฑ์ค 2178 ๋ฏธ๋ก ํ์ (Graph Traversal) (0) 2023.01.31 [Swift] ๋ฐฑ์ค 2667 ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (Graph Traversal) (0) 2023.01.31 [Swift] ๋ฐฑ์ค 9012 ๊ดํธ (Data Structure) (0) 2023.01.31