How to overcome TLE (time limit exceeded ) for python in CSES problem Counting rooms?

Viewed 302

Hello I am trying to solve Counting rooms problem under the graph section in cses problem set.

link to the question - https://cses.fi/problemset/task/1192

Its a simple no. of connected components in a graph problem which i am trying to solve using dfs(depth first search).

Here is my code

import sys

sys.setrecursionlimit(10000000)

directions = [(0,1),(0,-1),(1,0),(-1,0)]

def dfs(gird,i,j):
    for a,b in directions:
       x,y = i+a,j+b
       if 0 <= x and x < n and 0 <= y and y < m and gird[x][y] == '.':
          gird[x][y] = "#"
          dfs(gird,x,y)


if __name__ == "__main__":
     n,m = map(int,input().split())
     gird = [list(input()) for i in range(n)]

     count = 0
     for i in range(n):
         for j in range(m):
             if gird[i][j] == '.': 

                # making the visited points
                gird[i][j] = '#'
                dfs(gird,i,j)
                count += 1

     print(count)  

My solution is giving Tle for the test cases #9 #10 #17 all of these test cases have grid of 1000X1000 while there are more test case of this grid size which passes with ease while these test case are failing .

links to these test cases

Is there a way to further optimize my solution . A help would be really appreciated.

0 Answers
Related