Help me in solving Maximum Size graph problem

My issue

my code outputs the correct code, but I am getting a run time error (python)

My code

# cook your dish here

def dfs(grid, r, c, size):
    if r < 0 or c < 0 or r > len(grid) - 1 or c > len(grid[0]) - 1 or grid[r][c] == '0': return

    grid[r][c] = '0'
    size += 1
    dfs(grid, r - 1, c, size)
    dfs(grid, r + 1, c, size)
    dfs(grid, r, c - 1, size)
    dfs(grid, r, c + 1, size)
    return size
t = int(input())

for _ in range(t):
    N,M = map(int, input().split())
    
    grid = [[0] * N for i in range(M)]
    Chef = False
    total = 0
    
    for i in range(N):
        grid[i] = list(input())
    
    
    for rows in range(N):
        for cols in range(M):
            if grid[rows][cols] == '1':
                count = dfs(grid, rows, cols, 0)
                if Chef:
                    total += count
                Chef = not Chef
    
    print(total)

Learning course: Rise from 3* to 4*
Problem Link: CodeChef: Practical coding for everyone