๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] Swift 2468 ์•ˆ์ „ ์˜์—ญ BFS

by Jouureee 2022. 3. 11.

๋ฌธ์ œ :

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

 

2468๋ฒˆ: ์•ˆ์ „ ์˜์—ญ

์žฌ๋‚œ๋ฐฉ์žฌ์ฒญ์—์„œ๋Š” ๋งŽ์€ ๋น„๊ฐ€ ๋‚ด๋ฆฌ๋Š” ์žฅ๋งˆ์ฒ ์— ๋Œ€๋น„ํ•ด์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ผ์„ ๊ณ„ํšํ•˜๊ณ  ์žˆ๋‹ค. ๋จผ์ € ์–ด๋–ค ์ง€์—ญ์˜ ๋†’์ด ์ •๋ณด๋ฅผ ํŒŒ์•…ํ•œ๋‹ค. ๊ทธ ๋‹ค์Œ์— ๊ทธ ์ง€์—ญ์— ๋งŽ์€ ๋น„๊ฐ€ ๋‚ด๋ ธ์„ ๋•Œ ๋ฌผ์— ์ž ๊ธฐ์ง€ ์•Š๋Š”

www.acmicpc.net

 

๋ถ„์„ :

๋ฌธ์ œ์˜ ์•ˆ์ „ ์˜์—ญ์˜ ์ •์˜๋ฅผ ์ฒ˜์Œ์—” ์ดํ•ดํ•˜๊ธฐ ์–ด๋ ค์› ๋‹ค. ๊ทธ๋ž˜์„œ ์–ผ๋งŒํผ์˜ ์žฅ๋งˆ๊ฐ€ ๋‚ด๋ฆฐ๋‹ค๊ตฌ ? ํ–ˆ๋Š”๋ฐ ๋ชจ๋“  ์žฅ๋งˆ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ค ๊ฒ€์‚ฌํ•ด ์•ˆ์ „ ์˜์—ญ์ด ์ตœ๋Œ€๊ฐ€ ๋ ๋•Œ ์•ˆ์ „ ์˜์—ญ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ผ๋Š” ๋œป์ด์—ˆ๋‹ค.

bfs๋ฅผ ๋Œ์•„ visit๋ฐฐ์—ด์— false์ธ ์˜์—ญ์„ true๋กœ ๋งŒ๋“ค๊ณ  ๋๋‚ด๊ณ  ์˜ค๋ฉด bfsAll ํ•จ์ˆ˜์—์„œ ํ•˜๋‚˜์”ฉ cnt + 1 ํ•˜์—ฌ ์•ˆ์ „ ์˜์—ญ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์ค€๋‹ค.

๊ทธ ์ „์— visit ๋ฐฐ์—ด์„ ์•ˆ์ „ ์˜์—ญ ๋†’์ด 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด ์–ด๋Š ๋†’์ด๊นŒ์ง€ ๊ฒ€์‚ฌํ• ํ…๊ฐ€๊ฐ€ ๋ฌธ์ œ์ธ๋ฐ input์‹œ arr๋ฐฐ์—ด ์•ˆ์— ์ตœ๋Œ€๊ฐ’์„ maxNumber์— ๊ธฐ๋กํ•ด ๋‘”๋’ค ๋งค๋ฒˆ bfsAll ๋ฐฐ์—ด์„ ๋Œ๊ธฐ์ „ visit ๋ฐฐ์—ด์„ ์ดˆ๊ธฐํ™” ์‹œ์ผœ ์ฃผ์—ˆ๊ณ  ๋งˆ์ง€๋ง‰์— totalArea์— ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•˜๋„๋ก ํ–ˆ๋‹ค.

 

swift ํ’€์ด :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/03/11.
//

import Foundation
var n = Int(readLine()!)!
var arr: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)
var visit = Array(repeating: Array(repeating: false, count: n), count: n)
var dx = [-1, 1, 0, 0]
var dy = [0, 0, 1, -1]

func bfs(_ i: Int, _ j: Int){
   visit[i][j] = true
    var qu = [(Int, Int)]()
    qu.append((i, j))
    
    while(!qu.isEmpty){
        let nx = qu.last!.0
        let ny = qu.last!.1
        qu.removeLast()
        for i in 0..<4 {
            let nextX = nx + dx[i]
            let nextY = ny + dy[i]
            if(nextX >= n || nextX < 0 || nextY >= n || nextY < 0) { continue }
            if(visit[nextX][nextY]) { continue }
            //print("\(nextX) \(nextY)")
            visit[nextX][nextY] = true
            qu.append((nextX, nextY))
        }
        
    }
}

func bfsAll() -> Int {
    var cnt = 0;
    for i in 0..<n {
        for j in 0..<n {
            if(!visit[i][j]){
                bfs(i, j)
                cnt += 1
            }
        }
    }
    return cnt
}

var totalArea = 0
var maxNumber = 0
for i in 0..<n {
    let line = readLine()!.split(separator:  " ").map { Int($0)! }
    for j in 0..<line.count {
        arr[i][j] = line[j]
        if(arr[i][j] > maxNumber){
            maxNumber = arr[i][j]
        }
    }
}

for k in 0..<maxNumber {
    for i in 0..<n {
        for j in 0..<n {
            if(arr[i][j] <= k){
                visit[i][j] = true
            }
        }
    }
    totalArea = max(bfsAll(), totalArea)
    visit = Array(repeating: Array(repeating: false, count: n), count: n) // ๋‹ค์‹œ ์ดˆ๊ธฐํ™”
}
print(totalArea)โ€‹

 

 

๋Œ“๊ธ€