๋ฐ์ํ
๐ ๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/4963
๐ป ๋ฌธ์ ํ์ด
- ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ DFS๋ฌธ์ (BFS๋ ๊ฐ๋ฅ)
- ๊ทธ๋ํ๋ก ์ ๋ ฅ ๋ฐ์ ํ, 1์ธ ๊ณณ์ ์ ๋ถ ํ์ → ํ์ํ๋ฉด์ ํด๋น ์์น ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
- ๋ฐฉ๋ฌธ์ฒ๋ฆฌ ๋ ๊ณณ๋ค์ ๋์๋ค๋๋ค๊ฐ ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ ๊ณณ์ด ์์ผ๋ฉด count += 1
- ์ต์ข ์ ์ผ๋ก count ์ถ๋ ฅ
๐ป ์์ค์ฝ๋
let dx = [-1, 1, 0, 0, -1, -1, 1, 1]
let dy = [0, 0, -1, 1, -1, 1, -1, 1] //์ ์ ์ผ ์ค ์ผ์ชฝ์ ์ค๋ฅธ์ชฝ์ ์ผ์ชฝ์๋ ์ค๋ฅธ์ชฝ์๋
while true {
var count = 0
let wh = readLine()!.split(separator: " ").map{ Int(String($0))! }
if wh == [0, 0] {
break
}
var islandMap: [[Int]] = []
var visited = Array(repeating: Array(repeating: false, count: wh[0]), count: wh[1])
for _ in 0..<wh[1] {
islandMap.append(readLine()!.split(separator: " ").map { Int(String($0))! })
}
func dfs(_ x: Int, _ y: Int) {
for i in 0..<dx.count {
let nx = x + dx[i]
let ny = y + dy[i]
if nx < 0 || nx > wh[0]-1 || ny < 0 || ny > wh[1]-1 {
continue
} else {
if !visited[nx][ny] && islandMap[nx][ny] == 1 {
visited[nx][ny] = true
dfs(ny, nx)
}
}
}
}
// main
for i in 0..<wh[1] {
for j in 0..<wh[0] {
if islandMap[i][j] == 1 && !visited[i][j] {
visited[i][j] = true
dfs(i, j)
count += 1
}
}
}
print(count)
}
๋ฐ์ํ
'Algorithm > Baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] (Swift) 7576๋ฒ - ํ ๋งํ (BFS) (3) | 2022.06.23 |
---|---|
[๋ฐฑ์ค] (Swift) 2178๋ฒ - ๋ฏธ๋กํ์ (BFS ํ์ด) (0) | 2022.06.23 |
[๋ฐฑ์ค](Swift) 2667๋ฒ - ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (DFS์ ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ๋ฌธ์ ) (1) | 2022.05.27 |
[๋ฐฑ์ค] (Swift) 1707๋ฒ - ์ด๋ถ๊ทธ๋ํ (DFS๋ก ํ๊ธฐ!) (0) | 2022.05.25 |
[๋ฐฑ์ค] (Swift) 14889๋ฒ - ์คํํธ์ ๋งํฌ (DFS-๋ฐฑํธ๋ํน) (0) | 2022.05.23 |