Skip to content

Instantly share code, notes, and snippets.

@moatazshawky
Created September 27, 2016 07:46
Show Gist options
  • Save moatazshawky/ba8b5c89200800552aa876bf26c19501 to your computer and use it in GitHub Desktop.
Save moatazshawky/ba8b5c89200800552aa876bf26c19501 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class Main {
static char[][] map;
static boolean[][] visited;
static int count = 0;
static int mapW, mapH;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder s = new StringBuilder();
int ans = 0;
while ((mapH = in.nextInt()) != 0 && (mapW = in.nextInt()) != 0) {
in.nextLine();
map = new char[mapH][mapW];
visited = new boolean[mapH][mapW];
for (int i = 0; i < mapH; i++)
map[i] = in.nextLine().toCharArray();
for (int i = 0; i < mapH; i++) {
for (int j = 0; j < mapW; j++) {
if (!visited[i][j] && map[i][j] != '.') {
connectedComponent(i, j);
if (count == 1)
ans++;
count = 0;
}
}
}
s.append(ans).append("\n");
ans = 0;
}
System.out.print(s.toString());
in.close();
}
private static void connectedComponent(int i, int j) {
if (i < 0 || j < 0 || i > mapH - 1 || j > mapW - 1 || visited[i][j] || map[i][j]!='*')
return;
visited[i][j] = true;
count++;
connectedComponent(i, j - 1);
connectedComponent(i - 1, j - 1);
connectedComponent(i + 1, j - 1);
connectedComponent(i, j + 1);
connectedComponent(i + 1, j + 1);
connectedComponent(i - 1, j + 1);
connectedComponent(i - 1, j);
connectedComponent(i + 1, j);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment