DevYoon

[SWEA] 1949. ๋“ฑ์‚ฐ๋กœ ์กฐ์„ฑ (Python) ๋ณธ๋ฌธ

PS/SWEA

[SWEA] 1949. ๋“ฑ์‚ฐ๋กœ ์กฐ์„ฑ (Python)

gimewn 2022. 4. 7. 00:43

link ๐Ÿ”— https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PoOKKAPIDFAUq

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

 

1๏ธโƒฃ ๋“ฑ์‚ฐ๋กœ๋Š” ๊ฐ€์žฅ ๋†’์€ ๋ด‰์šฐ๋ฆฌ์—์„œ โžก๏ธ Max ๊ฐ’ ๊ตฌํ•ด์ฃผ๊ณ , ์ด์ค‘ for๋ฌธ์œผ๋กœ Max๊ฐ’๊ณผ ๊ฐ™๋‹ค๋ฉด dfs ๋Œ๋ ค์ฃผ๊ธฐ

2๏ธโƒฃ ๊ฐ€๋กœ or ์„ธ๋กœ๋กœ ์ด๋™, ๋†’์€ → ๋‚ฎ์€ โžก๏ธ ์ƒ ํ•˜ ์ขŒ ์šฐ, Branch 4

3๏ธโƒฃ ๋”ฑ ํ•œ ๊ณณ์„ ์ •ํ•ด ์ตœ๋Œ€ ๊ณต์‚ฌ ๊ฐ€๋Šฅ ๊นŠ์ด K๋งŒํผ โžก๏ธ ์ฒ˜์Œ์— K๋ณด๋‹ค ์ž‘์œผ๋ฉด ๋“ฑ์‚ฐ๋กœ๋ฅผ ์กฐ์„ฑํ•  ์ˆ˜ ์—†๋‹ค๊ณ  ์ดํ•ดํ–ˆ๋Š”๋ฐ, ๋ฌธ์ œ ํ’€๋ฉด์„œ ์ž˜๋ชป ์ดํ•ดํ–ˆ๋‹ค๋Š” ๊ฒƒ์„ ๊นจ๋‹ฌ์•˜๋‹ค.

4๏ธโƒฃ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ๊ธด ๊ธธ์ด โžก๏ธ Max_length

 

๐Ÿ’ฅ ์ฃผ์˜

  • ์ตœ๋Œ€ ๊ณต์‚ฌ ๊ฐ€๋Šฅ ๊นŠ์ด K๋Š” K๋งŒํผ ๊นŽ์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๋œป์ด๋‹ค. ๊ฐ€๋ น, 8์ธ ์‚ฐ์„ ๊นŽ์œผ๋ ค ํ•˜๊ณ  K๊ฐ€ 3์ด๋ผ๋ฉด 5๊นŒ์ง€๋งŒ ๊นŽ์„ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋‹ค.

 

def dfs(y, x, nowheight, cnt, check):
    global Max_length
    directy = [-1, 1, 0, 0]
    directx = [0, 0, -1, 1]
    for i in range(4):
        dy = directy[i]+y
        dx = directx[i]+x
        if 0 <= dy < N and 0 <= dx < N:
            if visit[dy][dx] == 1:continue # ๋ฐฉ๋ฌธํ•œ ์  ์žˆ์œผ๋ฉด X
            if mountain[dy][dx] < nowheight: # ์ด๋™ํ•˜๋ ค๋Š” ์‚ฐ์˜ ๋†’์ด๊ฐ€ ํ˜„์žฌ ์‚ฐ์˜ ๋†’์ด๋ณด๋‹ค ์ž‘์œผ๋ฉด
                visit[dy][dx] = 1
                dfs(dy, dx, mountain[dy][dx], cnt+1, check)
                visit[dy][dx] = 0
            else:
                # ์ด๋™ํ•˜๋ ค๋Š” ์‚ฐ์˜ ๋†’์ด์—์„œ ํ˜„์žฌ ์‚ฐ์˜ ๋†’์ด๋ฅผ ๋บ€ ๊ฐ’์ด ์ตœ๋Œ€ ๊ณต์‚ฌ ๊ฐ€๋Šฅ ๊นŠ์ด๋ณด๋‹ค ์ž‘์•„์•ผ ๋บ์„ ๋•Œ ์ด๋™ ๊ฐ€๋Šฅ
                if mountain[dy][dx]-nowheight < depth: 
                    if check != 1: # ํŒ ์  ์—†์œผ๋ฉด
                        visit[dy][dx] = 1
                        dfs(dy, dx, nowheight-1, cnt+1, 1)
                        visit[dy][dx] = 0

    if Max_length < cnt: # ๋” ์ด์ƒ ๋“ฑ์‚ฐ๋กœ๋ฅผ ๊ณต์‚ฌํ•  ์ˆ˜ ์—†์œผ๋ฉด
        Max_length = cnt # ์ตœ๋Œ€ ๊ธธ์ด ๋น„๊ต ๋ฐ ๊ฐฑ์‹ 
    return

t = int(input())
for tc in range(1, t+1):
    N, depth = map(int, input().split()) # ํ•œ ๋ณ€์˜ ๊ธธ์ด, ์ตœ๋Œ€ ๊ณต์‚ฌ ๊ฐ€๋Šฅ ๊นŠ์ด
    mountain = [list(map(int, input().split())) for _ in range(N)]
    visit = [[0]*N for _ in range(N)]
    Max = -2e18
    Max_length = -2e18
    # Max ๊ฐ’ ์ฐพ์•„์ฃผ๊ธฐ
    for i in range(N):
        Max = max(Max, max(mountain[i]))
    # Max์™€ ๊ฐ™์œผ๋ฉด dfs ๋Œ๋ ค์คŒ
    for y in range(N):
        for x in range(N):
            if mountain[y][x] == Max:
                visit[y][x] = 1
                dfs(y, x, mountain[y][x], 1, 0) # y, x, ํ˜„์žฌ ๋†’์ด, ๊ธธ์ด, ๊นŽ์•˜๋Š”์ง€
                visit[y][x] = 0
    print(f'#{tc} {Max_length}')