백준
1. Python
import sys
input = sys.stdin.readline
n = int(input())
seat = [[0]*n for _ in range(n)]
like = {}
result = 0
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
for _ in range(n*n):
data = list(map(int, input().split()))
like[data[0]] = data[1:]
x = 0
y = 0
max_like = -1
max_empty = -1
for i in range(n):
for j in range(n):
if seat[i][j] == 0:
likecnt = 0
emptycnt = 0
for k in range(4):
nx = i + dx[k]
ny = j + dy[k]
if 0 <= nx < n and 0 <= ny < n:
if seat[nx][ny] in data:
likecnt += 1
if seat[nx][ny] == 0:
emptycnt += 1
if max_like < likecnt or (max_like == likecnt and max_empty < emptycnt):
x = i
y = j
max_like = likecnt
max_empty = emptycnt
seat[x][y] = data[0]
for i in range(n):
for j in range(n):
cnt = 0
likelist = like[seat[i][j]]
for k in range(4):
nx = i + dx[k]
ny = j + dy[k]
if 0 <= nx < n and 0 <= ny < n:
if seat[nx][ny] in likelist:
cnt += 1
if cnt != 0:
result += 10 ** (cnt-1)
print(result)