Python

[Python] 알고리즘의 종류, 종류별 예제 _ 구현 (2/7)

shai-devit 2024. 9. 3. 09:00

예제1 (p.110)

상하좌우

#1
import time
n = map(int, input())
plan = list(map(str, input().split()))
start = time.time()
now = [1,1]
for move in plan:
    if move == "L":
        if now[1] - 1 != 0:
            now[1] -= 1
    elif move == "R":
        if now[1] + 1 != n:
            now[1] += 1
    elif move == "U":
        if now[0] - 1 != 0:
            now[0] -= 1
    elif move == "D":
        if now[0] + 1 != n:
            now[0] += 1

result = f"{now[0]} {now[1]}"
print(result)
print(f"time : {time.time()-start}s")

#2
import time
n = int(input())
plan = list(map(str, input().split()))
start = time.time()
now = [1,1]
Move_types = ["L", "R", "U", "D"]
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
for move in plan:
    for i in range(0, len(Move_types)):
        if move == Move_types[i]:
            tempx = now[0] + dx[i]
            tempy = now[1] + dy[i]
            if (tempx < 1)|(tempx > n)|(tempy < 1)|(tempy > n):
                continue
            else:
              now = [tempx, tempy]
result = f"{now[0]} {now[1]}"
print(result)
print(f"time : {time.time()-start}s")

예제2 (p.113)

시각

import time
n = int(input())
start = time.time()

result = 0
for h in range(0, n + 1):
    for m in range(0, 60):
        for s in range(0, 60):
            txt = f"{h}:{m}:{s}"
            if "3" in txt:
                result += 1
print(result)
print(f"time : {time.time()-start}s")

예제3 (p.115)

왕실의 나이트

import time

now = input()
start = time.time()
xcell = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ycell = [1,2,3,4,5,6,7,8]
now = [now[0], now[1]]
nowidx = xcell.index(now[0])
nowidy = ycell.index(int(now[1]))
pos = []
moves = [[2,1],[2,-1],[-2,1],[-2,-1],[1,2],[1,-2],[-1,2],[-1,-2]]
for move in moves:
    tempx = nowidx + move[0]
    tempy = nowidy + move[1]
    if (0 < tempx)&(tempx < 8)&(0 < tempy)&(tempy < 8):
        pos.append([xcell[tempx], tempy])
result = len(pos)
print(result)
print(f"time : {time.time()-start}s")

예제4 (p.118)

게임개발

n, m = map(int, input().split())
d = []
for i in range(n):
    d.append([0] * m)
nowx, nowy, now_dir = map(int, input().split())
d[nowx][nowy] = 1
maps = []
for i in range(0, n):
    maps.append(list(map(int, input().split())))
def turn_left(direction):
    direction -= 1
    if direction == -1:
        direction = 3
    return direction
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
turncount = 0
while(True):
    now_dir = turn_left(now_dir)
    turncount += 1
    tpx = nowx + dx[now_dir]
    tpy = nowy + dy[now_dir]
    if d[tpx][tpy] != 1 and maps[tpx][tpy] != 1:
        nowx, nowy = tpx, tpy
        d[nowx][nowy] = 1
        turncount = 0
    if turncount == 4:
        tpx = nowx - dx[now_dir]
        tpy = nowy - dy[now_dir]
        if maps[tpx][tpy] != 1:
            nowx, nowy = tpx, tpy
            turncount = 0
        else:
            break
result = 0
for i in range(0, len(d)):
    result += sum(d[i])
print(result)