Editorial for Counting Rooms
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Python
import sys
sys.setrecursionlimit(10**7)
n, m = map(int, input().split())
gridIsFloor = []
visitedRoom = [[False] * m for _ in range(n)]
for i in range(n):
row = input()
gridIsFloor.append([c == '.' for c in row])
for j in range(m):
if not gridIsFloor[i][j]:
visitedRoom[i][j] = True
def traverse(x, y):
if x < 0 or x >= n or y < 0 or y >= m:
return
if visitedRoom[x][y]:
return
if not gridIsFloor[x][y]:
return
visitedRoom[x][y] = True
traverse(x + 1, y)
traverse(x - 1, y)
traverse(x, y + 1)
traverse(x, y - 1)
numberOfRooms = 0
for i in range(n):
for j in range(m):
if visitedRoom[i][j]:
continue
numberOfRooms += 1
traverse(i, j)
print(numberOfRooms)
Java
import java.util.Scanner;
public class Main {
static int n, m;
static boolean[][] gridIsFloor;
static boolean[][] visitedRoom;
static void traverse(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m) return;
if (visitedRoom[x][y]) return;
if (!gridIsFloor[x][y]) return;
visitedRoom[x][y] = true;
traverse(x + 1, y);
traverse(x - 1, y);
traverse(x, y + 1);
traverse(x, y - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
gridIsFloor = new boolean[n][m];
visitedRoom = new boolean[n][m];
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
for (int j = 0; j < m; j++) {
char c = line.charAt(j);
if (c == '.') {
gridIsFloor[i][j] = true;
} else {
visitedRoom[i][j] = true;
}
}
}
int numberOfRooms = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visitedRoom[i][j]) continue;
numberOfRooms++;
traverse(i, j);
}
}
System.out.println(numberOfRooms);
sc.close();
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int n, m;
bool gridIsFloor[1005][1005];
bool visitedRoom[1005][1005];
void traverse(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m) return;
if (visitedRoom[x][y]) return;
if (!gridIsFloor[x][y]) return;
visitedRoom[x][y] = true;
traverse(x + 1, y);
traverse(x - 1, y);
traverse(x, y + 1);
traverse(x, y - 1);
}
signed main() {
cin.sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c;
cin >> c;
if (c == '.') {
gridIsFloor[i][j] = true;
} else visitedRoom[i][j] = true;
}
}
int numberOfRooms = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visitedRoom[i][j]) continue;
numberOfRooms++;
traverse(i, j);
}
}
cout << numberOfRooms << endl;
}
Comments