Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 2178๋ฒˆ - ๋ฏธ๋กœํƒ์ƒ‰ (BFS ํ’€์ด)

๊ฐ์ž ๐Ÿฅ” 2022. 6. 23. 10:21
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฌธ์ œ ๋งํฌ

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

 

2178๋ฒˆ: ๋ฏธ๋กœ ํƒ์ƒ‰

์ฒซ์งธ ์ค„์— ๋‘ ์ •์ˆ˜ N, M(2 ≤ N, M ≤ 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” M๊ฐœ์˜ ์ •์ˆ˜๋กœ ๋ฏธ๋กœ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์ˆ˜๋“ค์€ ๋ถ™์–ด์„œ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

๐Ÿ’ป ๋ฌธ์ œ ํ’€์ด

๊ธฐ๋ณธ์ ์ด BFS ๋ฌธ์ œ์ด๋‹ค. ๋ฏธ๋กœ๋ฅผ ๊ฐ€์ค‘์น˜ ์—†๋Š” ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋กœ ๋ณธ๋‹ค๋ฉด, ๊ฐ€์ค‘์น˜์—†๋Š” ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„์—์„œ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” BFS ํƒ์ƒ‰ ๋ฐฉ๋ฒ•์„ ์ด์šฉํ•˜๋ฉด๋œ๋‹ค!

  • ์ฒ˜์Œ ์ž…๋ ฅ๋ฐ›๋Š” n๊ณผ m์„ nm ๋ฐฐ์—ด๋กœ ์ž…๋ ฅ๋ฐ›์•„์„œ nm[0], nm[1] ๋กœ ์‚ฌ์šฉํ•˜์˜€๋‹ค. 
  • dx, dy ๋Š” ์ƒํ•˜์ขŒ์šฐ ๋ฐฉํ–ฅ์„ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฉํ–ฅํ‚ค! ์ด๋‹ค.
  • arr๋Š” ์ž…๋ ฅ๋ฐ›๋Š” ๋ฏธ๋กœ
  • visited๋Š” ๋ฏธ๋กœ์—์„œ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์•ˆํ–ˆ๋Š”์ง€ T/F ๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฐ์—ด
  • distance๋Š” ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ• ๋•Œ ํ•˜๋‚˜์”ฉ +1 ํ•ด์„œ ๋งˆ์ง€๋ง‰์— distance[n][m]์œผ๋กœ ๋‹ต์„ ์ถœ๋ ฅํ•ด ์ค„ ๊ฒƒ์ด๋‹ค.

๊ธฐ๋ณธ์ ์ธ bfs ๋ฌธ์ œ๋กœ ๋”์ด์ƒ queue๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์„๋•Œ๊นŒ์ง€ while๋ฌธ์„ ๋Œ๋ ค์„œ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ’ป ์†Œ์Šค์ฝ”๋“œ

https://github.com/deslog/Algorithm/blob/main/Algorithm/Boj/2178_%EB%AF%B8%EB%A1%9C%ED%83%90%EC%83%89/main.swift

 

GitHub - deslog/Algorithm

Contribute to deslog/Algorithm development by creating an account on GitHub.

github.com

//
//  File.swift
//  Algorithm
//
//  Created by ์ด์ง€์ˆ˜ on 2022/06/23.
//

var nm = readLine()!.split(separator: " ").map { Int(String($0))! }

let dx = [0, 0, -1, 1]
let dy = [-1, 1, 0, 0] // ์ƒํ•˜์ขŒ์šฐ

var arr = [[Int]]()
var visited = Array(repeating: Array(repeating: false, count: nm[1]), count: nm[0])
var distance = Array(repeating: Array(repeating: 0, count: nm[1]), count: nm[0])

for _ in 0..<nm[0] {
    var temp = Array(readLine()!).map { Int(String($0))! }
    arr.append(temp)
}

func bfs() {
    distance[0][0] = 1
    visited[0][0] = true
    
    var queue: [[Int]] = [[0,0]]
    
    while !queue.isEmpty {
        let pop = queue.removeFirst()
        
        let x = pop[0]
        let y = pop[1]
        
        for i in 0..<4 {
            let nx = x + dx[i]
            let ny = y + dy[i]
            
            if nx >= 0 && nx < nm[0] && ny >= 0 && ny < nm[1] {
                if !visited[nx][ny] && arr[nx][ny] == 1 {
                    distance[nx][ny] = distance[x][y] + 1
                    
                    visited[nx][ny] = true
                    queue.append([nx, ny])
                }
            }
        }
    }
}

bfs()
print(distance[nm[0]-1][nm[1]-1])

 

๋ฐ˜์‘ํ˜•