-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c492e10
commit 19989af
Showing
1 changed file
with
28 additions
and
49 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,51 +1,30 @@ | ||
import Foundation | ||
|
||
func solution(_ maps: [[Int]]) -> Int { | ||
var maps = maps | ||
let dx = [-1, 1, 0, 0] | ||
let dy = [0, 0, -1, 1] | ||
let rowCount = maps.count | ||
let colCount = maps[0].count | ||
|
||
func bfs(_ x: Int, _ y: Int) -> Int { | ||
var queue = [(x, y)] | ||
var index = 0 | ||
|
||
while index < queue.count { | ||
let (x, y) = queue[index] | ||
index += 1 | ||
|
||
for i in 0..<4 { | ||
let nx = x + dx[i] | ||
let ny = y + dy[i] | ||
|
||
if nx < 0 || nx >= rowCount || ny < 0 || ny >= colCount { | ||
continue | ||
} | ||
|
||
if maps[nx][ny] == 0 { | ||
continue | ||
} | ||
|
||
if maps[nx][ny] == 1 { | ||
from collections import deque | ||
def solution(maps): | ||
answer = 0 | ||
|
||
dx = [-1, 1, 0, 0] | ||
dy = [0, 0, -1, 1] | ||
|
||
def bfs(x, y): | ||
queue = deque() | ||
queue.append((x, y)) | ||
|
||
while queue: | ||
x, y = queue.popleft() | ||
|
||
for i in range(4): | ||
nx = x + dx[i] | ||
ny = y + dy[i] | ||
|
||
if nx < 0 or nx >= len(maps) or ny < 0 or ny >= len(maps[0]): continue | ||
|
||
if maps[nx][ny] == 0: continue | ||
|
||
if maps[nx][ny] == 1: | ||
maps[nx][ny] = maps[x][y] + 1 | ||
queue.append((nx, ny)) | ||
} | ||
} | ||
} | ||
|
||
return maps[rowCount - 1][colCount - 1] | ||
} | ||
|
||
let answer = bfs(0, 0) | ||
return answer == 1 ? -1 : answer | ||
} | ||
|
||
// 예시 호출 | ||
let maps = [ | ||
[1, 0, 1, 1, 1], | ||
[1, 0, 1, 0, 1], | ||
[1, 1, 1, 0, 1], | ||
[0, 0, 0, 0, 1] | ||
] | ||
print(solution(maps)) // 출력: 11 | ||
|
||
return maps[len(maps)-1][len(maps[0])-1] | ||
|
||
answer = bfs(0, 0) | ||
return -1 if answer == 1 else answer |