4

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.

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 1
    An efficient algorithm to find the connected components of a graph is presented in my answer here `https://stackoverflow.com/a/68317177/16582 – ravenspoint Jul 14 '21 at 19:11

0 Answers0