티스토리 뷰
0,0 에서 시작해서 mapsize, mapsize 까지 가기 위한 최단거리를 구하는 문제이다.
BFS는 공식과도 같다 하여 BFS알고리즘
을 검색하여 참고하여 코드를 구현 하였다.
# https://programmers.co.kr/learn/courses/30/lessons/1844
# BFS를 써야 풀 수 있는 문제
from collections import deque
def nextXY(n, maps, sizeY, sizeX) :
y = n[0]
x = n[1]
depth = n[2]
nextque = []
if y - 1>= 0 and maps[y - 1][x] != 0 : #up
nextque.append([y - 1, x, depth + 1])
if y + 1 < sizeY and maps[y + 1][x] != 0 : #down
nextque.append([y + 1, x, depth + 1])
if x + 1 < sizeX and maps[y][x + 1] != 0 : #right
nextque.append([y, x + 1, depth + 1])
if x - 1 >= 0 and maps[y][x - 1] != 0 : #left
nextque.append([y, x - 1, depth + 1])
return nextque
def isFinish(y, x, sizeY, sizeX) :
if y == sizeY -1 and x == sizeX - 1 :
return True
else :
return False
def solution(maps):
queue = deque([[0,0,1]])
sizeY = len(maps)
sizeX = len(maps[0])
while queue :
n = queue.popleft()
if maps[n[0]][n[1]] != 0 :
if isFinish(n[0], n[1], sizeY, sizeX) :
return n[2]
maps[n[0]][n[1]] = 0
queue += nextXY(n, maps, sizeY, sizeX)
print(queue)
return -1
print(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]))
print(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]]))
https://cyc1am3n.github.io/2019/04/26/bfs_dfs_with_python.html
[Daily PS] 파이썬으로 구현하는 BFS와 DFS
파이썬으로 BFS와 DFS를 구현하는 내용입니다.
cyc1am3n.github.io
'ALGORITHM > Programmers' 카테고리의 다른 글
[프로그래머스] 프렌즈4블록.py (0) | 2021.11.15 |
---|---|
[프로그래머스] N개의 최소공배수.go (0) | 2021.11.01 |
[ 파이썬 ] 서울에서 김서방 찾기 (0) | 2020.05.01 |
[ 파이썬 ] 문자열 다루기 기본 (0) | 2020.05.01 |
[Programmers] 탑 (0) | 2019.11.17 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 소프트웨어 장인
- 백준
- Python
- 의대 신경학 강의
- query
- django
- for-else
- go
- ManyToMany
- 독후감
- dfs
- go context
- sql lite
- 문자열 뒤집기
- 파이썬
- stdout
- leetcode
- gunicorn
- Two Scoops of Django
- 팰린드롬수
- conTeXt
- taggit
- 프로그래머스
- 방금그곡
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함