CSES - Shared codeLink to this code: https://cses.fi/paste/bbe61433a419cb2a9d44e0/

import java.util.Scanner;
import java.util.Stack;

public class CountingRooms {
	
	public static void main(String[] gg)
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		
		char[][] mat = new char[n][m];
		
		for(int i = 0; i < n;i++)
		{
			mat[i]=sc.next().toCharArray();
		}
		int res = countRooms(mat, n, m);
		System.out.println(res);
	}
	
	private static int countRooms(char[][] graph, int n, int m)
	{
		
		boolean vis[][] = new boolean[n][m];
		int count = 0;
		for(int i = 0; i<n;i++)
		{
			for(int j = 0;j < m;j++)
			{
				if(graph[i][j] == '.' && !vis[i][j])
				{
					dfs(graph, i, j,  vis);
					count++;
				}
			}
		}
		return count;
	}
	
	private static void dfs(char[][] graph, int srx, int sry, boolean[][] vis)
	{
		Stack<Pair> st = new Stack<>();
		st.add(new Pair(srx, sry));
		int n = graph.length;
		int m = graph[0].length;
		
		vis[srx][sry] = true;
		
		while(!st.isEmpty())
		{
			Pair p = st.pop();
			int curX = p.first;
			int curY = p.second;
			

			int x[] = new int[] {-1,0,0,+1};
			int y[] = new int[] {0,-1,+1,0};
			
			for(int i = 0;i<x.length;i++)
			{
				int nX = curX + x[i];
				int nY = curY + y[i];
				
				if(nX >= 0 && nY >=0 && nX < n && nY < m  && graph[nX][nY] == '.' && !vis[nX][nY])
				{
					st.push(new Pair(nX, nY));
					vis[nX][nY] = true;
				}
			}
		}
	}
	
}

class Pair 
{
	int first, second;
	
	public Pair(int first, int second)
	{
		this.first = first;
		this.second = second;
	}
}