ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

2186๋ฒˆ: ๋ฌธ์žํŒ

์ฒซ์งธ ์ค„์— N(1 ≤ N ≤ 100), M(1 ≤ M ≤ 100), K(1 ≤ K ≤ 5)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” M๊ฐœ์˜ ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ด๋Š” N×M ํฌ๊ธฐ์˜ ๋ฌธ์žํŒ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ๋‹ค์Œ ์ค„์—๋Š” 1์ž ์ด์ƒ 80์ž ์ดํ•˜์˜

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ๋ชฉํ‘œ๊ฐ€ ๋˜๋Š” ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋ฅผ ์œ„ํ•ด์„œ `์ƒ, ํ•˜, ์ขŒ, ์šฐ`๋กœ K ๋งŒํผ์”ฉ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹จ์ˆœํžˆ DFS๋ฅผ ํ†ตํ•ด ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๊ฒŒ ๋˜๋ฉด ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ํ†ตํ•ด ์ด๋ฏธ ์ฒดํฌํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ผ๋ฉด ํ•ด๋‹น ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฒดํฌํ•˜์ง€ ์•Š์•„์•ผ(๊ฐ€์ง€์น˜๊ธฐ) ํ•œ๋‹ค.

 

 ์ฒ˜์Œ์—๋Š” `dirs = ((0, 1), (0, -1), (-1, 0), (1, 0))`๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•œ ๋ฐฉํ–ฅ์”ฉ ์ฒดํฌํ•˜๋„๋ก ํ•˜์˜€๋”๋‹ˆ Python3์—์„œ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค. ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ, ๋ฐฉํ–ฅ์„ ์ ‘๊ทผํ•  ๋•Œ, `next_x`, `next_y`์— ๋”ฐ๋ผ ๋‘ ๊ฐ€์ง€์˜ ๊ฐ€์ง€๋กœ ๋ป—๋Š” ๊ฒฝ์šฐ๋กœ ํ‘ธ๋Š” ๊ฒƒ์ด ๋” ํšจ์œจ์ ์ด๋ผ๋Š” ๊ฒƒ์„ ์•Œ๊ณ  ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์˜€๋‹ค.

 

์ฝ”๋“œ

 sys import stdin


def dfs(loc, idx):
    global answer
    x, y = loc
    
    # ๊ฐ€์ง€์น˜๊ธฐ 1: ์ด๋ฏธ ์ฒดํฌํ•œ ๊ฒฝ์šฐ
    if check[x][y][idx] != -1:
        return check[x][y][idx]
    
    # ๊ฐ€์ง€์น˜๊ธฐ 2: target ๋ฌธ์ž์™€ ์ผ์น˜ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ
    if board[x][y] != target[idx]:
        check[x][y][idx] = 0
        return 0
    
    # ์ฐพ๋Š” ๋ฌธ์ž์™€ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ
    if idx == len(target) - 1:
        return 1

    cur_answer = 0
    for k in range(-K, K + 1):
        if not k:
            continue

        next_x, next_y = x + k, y + k

        if 0 <= next_x < N:
            cur_answer += dfs((next_x, y), idx + 1)
        if 0 <= next_y < M:
            cur_answer += dfs((x, next_y), idx + 1)

    check[x][y][idx] = cur_answer

    return check[x][y][idx]


if __name__ == '__main__':
    answer = 0
    N, M, K = map(int, stdin.readline().split())
    board = [stdin.readline().strip() for _ in range(N)]
    target = stdin.readline().strip()

    dirs = ((0, 1), (0, -1), (-1, 0), (1, 0))
    check = [[[-1] * len(target) for _ in range(M)] for _ in range(N)]

    for i in range(N):
        for j in range(M):
            if board[i][j] == target[0]:
                answer += dfs((i, j), 0)

    print(answer)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€