Coding/Python
- 사전 및 집합 자료형 2023.03.16
- 반복된 숫자 지우기...특정의 여러 원소 제거하기 2023.03.16
- DFS#2 2023.03.16
- BFS#2 2023.03.16
- math 2023.03.15
- Python Error 2023.03.15
사전 및 집합 자료형
반복된 숫자 지우기...특정의 여러 원소 제거하기
DFS#2
o DFS 유형
n, m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
res = 0
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
def dfs(x, y):
if(x <= -1 or x >= n or y <= -1 or y >= m):
return False
ifgraph[x][y] == 0:
graph[x][y] = 1
for i in range(4):
dfs(x+dx[i],y+dy[i])
return True
return False
for i in range(n):
for j in range(m):
if dfs(i, j) == True:
res += 1
print(res)
예제) 4 5
00110
00011
11111
00000
#답3
BFS#2
o BFS
from collections import deque
n, m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
dx = [0, 0, -1, 1] #상하좌우 순서임 x라서 좌우만
dy = [1, -1, 0, 0]
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 ny < 0 or nx >= n or ny >= m):
continue
if (graph[nx][ny] == 0):
continue
if (graph[nx][ny] == 1):
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
return graph[n - 1][m - 1]
print(BFS(0, 0)) #답 10
ex) 5 6
101010
111111
000011
111111
111111
math
import math
Python Error
- ValueError