[정답 코드]
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
matrix = []
memo = [[0] * n for _ in range(n)]
# making matrix and memo
for i in range(n):
matrix.append(list(map(int, input().split())))
memo[i][0] = matrix[i][0]
for j in range(1, n):
memo[i][j] = memo[i][j - 1] + matrix[i][j]
if i != 0:
for j in range(n):
memo[i][j] += memo[i - 1][j]
# input x1, y1, x2, y2
for i in range(m):
res = 0
x1, y1, x2, y2 = map(int, input().split())
res += memo[x2 - 1][y2 - 1]
if y1 >= 2:
res -= memo[x2 - 1][y1 - 2]
if x1 >= 2:
res -= memo[x1 - 2][y2 - 1]
if x1 >= 2 and y1 >= 2:
res += memo[x1 - 2][y1 - 2]
print(res)
[풀이]
[오류 해결]
python list의 index에 음수가 들어가면 뒤에서부터 indexing하여 접근하기 때문에 조심해야한다. 이를 방지하기 위해 if y1 >= 2
등의 조건을 달아주었다.
[적용 자료구조 및 알고리즘]