1+ import sys
2+ input = sys .stdin .readline
3+
4+ N = int (input ())
5+ A = [list (map (int , input ().split ())) for _ in range (N )] # NxN 격자
6+
7+ # 방향: 좌 -> 하 -> 우 -> 상
8+ directions = [(- 1 , 0 ), (0 , 1 ), (1 , 0 ), (0 , - 1 )]
9+
10+ # 모래 이동 비율 (왼쪽으로 이동할 때 기준)
11+ sand_ratio = [
12+ (- 1 , 1 , 0.01 ), (1 , 1 , 0.01 ),
13+ (- 1 , 0 , 0.07 ), (1 , 0 , 0.07 ),
14+ (- 2 , 0 , 0.02 ), (2 , 0 , 0.02 ),
15+ (- 1 , - 1 , 0.10 ), (1 , - 1 , 0.10 ),
16+ (0 , - 2 , 0.05 ),
17+ (0 , - 1 , 'alpha' ) # a: 남은 모래를 놓을 위치
18+ ]
19+
20+ out_sand = 0 # 격자 밖으로 나간 모래의 양
21+
22+ # 주어진 방향에 따라 (dx, dy)를 회전
23+ def rotate_dir (dx , dy , dir ):
24+ for _ in range (dir ):
25+ dx , dy = dy , - dx # 90도 회전
26+ return dx , dy
27+
28+ # 모래를 현재 위치 (x,y)에서 dir 방향으로 퍼뜨림
29+ def spread_sand (x , y , dir ):
30+ global out_sand
31+ total_sand = A [x ][y ] # 현재 위치의 모래 양
32+ spread_sum = 0 # 흩날린 모래 총합
33+ A [x ][y ] = 0 # 현재 위치 모래를 먼저 없애줌
34+
35+ for dx , dy , ratio in sand_ratio :
36+ if ratio == 'alpha' : # a 위치일 때 처리
37+ continue
38+ # 현재 방향(dir)에 맞게 회전 적용
39+ nx , ny = rotate_dir (dx , dy , dir ) # 회전 적용
40+ nx , ny = x + dx , y + dy # 이동 좌표 계산
41+ sand = int (total_sand * ratio ) # 소수점 버림
42+
43+ if 0 <= nx < N and 0 <= ny < N :
44+ A [nx ][ny ] += sand # 격자 내에 있으면 더하기
45+ else :
46+ out_sand += sand # 격자 밖이면 밖으로 나간 모래에 추가
47+
48+ spread_sum += sand # 흩날린 모래 총합 증가
49+
50+ # 남은 모래를 a 위치에 배치
51+ dx , dy = rotate_dir (sand_ratio [- 1 ][0 ], sand_ratio [- 1 ][1 ], dir )
52+ alpha_x , alpha_y = x + dx , y + dy
53+ remaining_sand = total_sand - spread_sum # 남은 모래 계산
54+
55+ if 0 <= alpha_x < N and 0 <= alpha_y < N :
56+ A [alpha_x ][alpha_y ] += remaining_sand
57+ else :
58+ out_sand += remaining_sand # 격자 밖이면 밖으로 나간 모래에 추가
59+
60+
61+ x , y = N // 2 , N // 2 # 시작위치 (중앙)
62+ steps = 1 # 이동거리
63+ dir = 0 # 방향 인덱스 (0:좌, 1:하, 2:우, 3:상)
64+
65+ while (x , y ) != (0 , 0 ): # (1,1)까지 이동
66+ for _ in range (2 ): # 같은 step 크기로 두 번 이동 (좌->하, 우->상)
67+ for _ in range (steps ):
68+ x += directions [dir ][0 ]
69+ y += directions [dir ][1 ]
70+
71+ spread_sand (x , y , dir ) # 모래 퍼뜨리기
72+
73+ if x == 0 and y == 0 : # (1,1) 도착하면 종료
74+ break
75+
76+ dir = (dir + 1 ) % 4 # 방향 변경
77+
78+ steps += 1 # step 크기 중가
79+
80+ print (out_sand )
81+
0 commit comments