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
https://cses.fi/file/750a493af574c1476eeeb0b29366fbecf5acf483cb80b33de3a32a2683a9054e/1/1/
https://cses.fi/file/de43e0698860b02af4ce18d9df03d195a2a6e053b31a89dc99cd70c674457e8c/1/1/
https://cses.fi/file/697e035998f21466a14cb2b6214a49f3ee83cfdd7d924bf5607918e64092a3af/1/1/
Is there a way to further optimize my solution . A help would be really appreciated.