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

 

16724번: 피리 부는 사나이

첫 번째 줄에 지도의 행의 수를 나타내는 N(1 ≤ N ≤ 1,000)과 지도의 열의 수를 나타내는 M(1 ≤ M ≤ 1,000)이 주어진다. 두 번째 줄부터 N개의 줄에 지도의 정보를 나타내는 길이가 M인 문자열이 주

www.acmicpc.net

 

 

 

 

 

 

 

import sys
from collections import deque

input = sys.stdin.readline

n,m = map(int,input().split())

Map = [list(input().strip()) for _ in range(n)]
check = [[0] * m for _ in range(n)]
ans=0

def dfs(y,x):
    global ans
    check[y][x] = 1
    ny,nx = y, x
    if Map[y][x] == 'D':
        ny += 1
    elif Map[y][x] == 'U':
        ny -= 1
    elif Map[y][x] == 'R':
        nx += 1
    elif Map[y][x] == 'L':
        nx -= 1

    if check[ny][nx] == 1: ans += 1
    if check[ny][nx] == 0: dfs(ny,nx)
    check[y][x] = 2
    

#사이클의 개수 세기
for i in range(n):
    for j in range(m):
        if check[i][j] == 0:
            dfs(i,j)
print(ans)

 

 

 

 

+ Recent posts