๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[SWEA] 1215. ํšŒ๋ฌธ1/Python - D3

by The Future Engineer, Lucy 2024. 11. 16.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14QpAaAAwCFAYi

 

SW Expert Academy

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

swexpertacademy.com

์„ฑ๋Šฅ ์š”์•ฝ

์žฌ๊ท€ํ˜ธ์ถœ โžก๏ธ ๋ฉ”๋ชจ๋ฆฌ: 45,056 KB, ์‹œ๊ฐ„: 117 ms, ์ฝ”๋“œ๊ธธ์ด: 696 Bytes
๋ฐ˜๋ณต๋ฌธ โžก๏ธ ๋ฉ”๋ชจ๋ฆฌ: 44,812 KB, ์‹œ๊ฐ„: 139 ms, ์ฝ”๋“œ๊ธธ์ด: 407 Bytes

โœ๐Ÿปํ’€์ด

์„ธ๋กœ๋กœ ์ด์–ด์ง„ ํšŒ๋ฌธ์„ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ธฐ ์œ„ํ•ด ์ „์น˜ํ–‰๋ ฌ๋กœ ๋ฐ”๊พผ๋‹ค.
๊ธฐ๋ณธ์ ์œผ๋กœ ๊ธ€์žํŒ์˜ ํฌ๊ธฐ๋Š” 8์ธ๋ฐ l์„ ํšŒ๋ฌธ์˜ ๊ธธ์ด๋ผ๊ณ  ํ•˜๋ฉด 8-l+1 ๋งŒํผ ๋ฐ˜๋ณตํ•˜์—ฌ ๊ธ€์ž๋งŒ๋“ ๋‹ค.
๊ทธ ๊ธ€์ž๊ฐ€ ํšŒ๋ฌธ์ธ ๊ฒฝ์šฐ 1์„ ๋”ํ•œ๋‹ค.

๐Ÿ’ป์ฝ”๋“œ

# ์žฌ๊ท€ํ˜ธ์ถœ
def palindromic(y, x, s):
    if len(s) == l:
        if s == "".join(s[::-1]):
            return 1
        else:
            return 0
 
    return palindromic(y, x + 1, s + board[y][x])
 
def t_palindromic(y, x, s):
    if len(s) == l:
        if s == "".join(s[::-1]):
            return 1
        else:
            return 0
 
    return t_palindromic(y, x + 1, s + t_board[y][x])
 
 
for tc in range(1, 11):
    l = int(input())
    board = [list(input()) for _ in range(8)]
    t_board = list(map(list, zip(*board)))
 
    res = 0
    for i in range(8):
        for j in range(8-l+1):
            res += palindromic(i, j, "")
            res += t_palindromic(i, j, "")
 
    print(f"#{tc} {res}")
# ๋ฐ˜๋ณต๋ฌธ
for tc in range(1, 11):
    l = int(input())
    board = [list(input()) for _ in range(8)]
    t_board = list(map(list, zip(*board)))

    res = 0
    for i in range(8):
        for j in range(8-l+1):
            s = board[i][j:j+l]
            if s == s[::-1]:
                res += 1
            t_s = t_board[i][j:j+l]
            if t_s == t_s[::-1]:
                res += 1

    print(f"#{tc} {res}")

๐Ÿ“ํ›„๊ธฐ

์ฒ˜์Œ์—๋Š” backtracking์ธ๊ฐ€ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๋ฐฉ๋ฌธ ํ‘œ์‹œ๋ฅผ ๊ตณ์ด ํ•  ํ•„์š”๊ฐ€ ์—†์–ด์„œ ์ด๊ฑธ backtracking์ด๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ์„๊นŒ ์‹ถ์–ด์„œ visit์€ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ๊ทธ๋ƒฅ ์žฌ๊ท€๋กœ ์ƒ๊ฐํ•˜๊ณ  ํ’€์—ˆ๋‹ค. ๋ฌธ์ œ ๋Œ“๊ธ€๋ณด๋‹ˆ๊นŒ ์‚ผ์ค‘๋ฐ˜๋ณต๋ฌธ์ด๋ผ๋Š” ๋ง๋„ ์žˆ์–ด์„œ ์‚ผ์ค‘๋ฐ˜๋ณต๋ฌธ์œผ๋กœ๋„ ํ’€์–ด๋ณด์•˜๋‹ค. ์‹œ๊ฐ„์€ ์žฌ๊ท€๊ฐ€ ์กฐ๊ธˆ ๋œ ๊ฑธ๋ฆฌ๋Š” ๊ฒƒ ๊ฐ™์ง€๋งŒ ๋ฉ”๋ชจ๋ฆฌ๋Š” ์‚ผ์ค‘๋ฐ˜๋ณต๋ฌธ์ด ๋œ ์ฐจ์ง€ํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

728x90
๋ฐ˜์‘ํ˜•