Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save skashan-ali/ca731af9f640765d4560decc4e0cdff3 to your computer and use it in GitHub Desktop.
Save skashan-ali/ca731af9f640765d4560decc4e0cdff3 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class CountStar {
static char[][] rowCol;
static boolean[][] visited;
static int count = 0;
static int row, col;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCase=0;
int ans = 0;
while ((row = in.nextInt()) != 0 && (col = in.nextInt()) != 0) {
testCase++;
in.nextLine();
rowCol = new char[row][col];
visited = new boolean[row][col];
for (int i = 0; i < row; i++)
rowCol[i] = in.nextLine().toCharArray();
// Iterating to the row and col
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (!visited[i][j] && rowCol[i][j] != '#') {
connectedComponent(i, j);
if (count >= 1)
ans++;
count = 0;
}
}
}
System.out.println("Case " + testCase + ": " + ans);
ans = 0;
}
in.close();
}
private static void connectedComponent(int i, int j) {
if (i < 0 || j < 0 || i > row - 1 || j > col - 1 || visited[i][j] || rowCol[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