New update is available. Click here to update.

Last Updated: 19 Mar, 2021

Moderate

```
A house is represented by a matrix where β\β and β/β represent a wall and blank space is empty space. We will consider two rooms different if we will be unable to reach another room.
```

```
Input:
[
β /β
β/\β
]
Output: 3
Explanation: 2 X 2 house is shown below:
```

```
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains the βNβ number of strings.
The next βNβ lines of each test case contain a single string of length βNβ.
```

```
For each test case, return the number of the separate rooms.
The output of each test case will be printed in a separate line.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 5
2 <= N <= 30
Time limit: 1 sec
```

Approaches

First, we will convert our given matrix to a more convenient one so that it would be easy for us to find the number of components in the graph(i.e., Number of rooms). Then we can find the number of components either by depth-first search or disjoint union.

Just magnify each box of the house three times.

The steps are as follows:

- Declare a new matrix βnewhouseβ of size 3 * βNβ where βNβ is the size of the given matrix.
- Initialize matrix with all zeros.
- Iterate through the given βNβ strings and fill the βnewHouseβ as follows:
- Let current character isβ\β and its position is (i,j), then
- We will assign 1 to (3 * i, 3 * j), (3 * i + 1, 3 * j + 1), (3 * i + 2,3 * j + 2)
- Now, if our current character is β/β and its position is (i , j), then
- We will assign 1 to (3 * i, 3 * j + 2), (3 * i + 1, 3 * j + 1), (3 * i + 2, 3 * j)

After this we will count the number of components by using depth-first search or union-find.

void βDFSβ(int βiβ, int βjβ, vector<vector<int>> &βnewHouseβ, int βNβ)

{

newHouse[i][j] := 1

We will call dfs again on the following values ('i' + 1, βjβ), ('i' - 1, βjβ), ('i', βjβ + 1), ('i', βjβ - 1), if these values exist in the table and βnewHouseβ value is 0.

dfs(a, b, βnewHouseβ, βNβ);

}

We are using DFS because it is easy to understand and implement.