Skip to content

Instantly share code, notes, and snippets.

@hugoangeles0810
Created August 17, 2016 18:03
Show Gist options
  • Select an option

  • Save hugoangeles0810/17bb4683d52f8c0b4dc6e94706cfd2bc to your computer and use it in GitHub Desktop.

Select an option

Save hugoangeles0810/17bb4683d52f8c0b4dc6e94706cfd2bc to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
class Main{
public static void main(String[] args) throws FileNotFoundException, IOException {
char[][] matriz;
String[] campos;
int contador;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int casos = Integer.parseInt(readLine(br)[0]);
for (int i = 0; i < casos; i++) {
contador = 0;
campos = readLine(br);
matriz = new char[Integer.parseInt(campos[0])][];
for (int j = 0; j < matriz.length; j++) {
matriz[j] = readLine(br)[0].toCharArray();
}
for (int j = 0; j < matriz.length; j++) {
for (int k = 0; k < matriz[0].length; k++) {
if (matriz[j][k] == 'M') {
contador++;
recursivo(matriz, j, k);
}
}
}
System.out.println("Caso #" + (i + 1) + ": " + contador);
}
}
private static void recursivo(char[][] matriz, int j, int k) {
matriz[j][k] = ' ';
if (si(j - 1, k, matriz) && matriz[j - 1][k] == 'M') { // Norte
recursivo(matriz, j - 1, k);
}
if (si(j - 1, k - 1, matriz) && matriz[j - 1][k - 1] == 'M') { // NorOeste
recursivo(matriz, j - 1, k - 1);
}
if (si(j, k - 1, matriz) && matriz[j][k - 1] == 'M') { // Oeste
recursivo(matriz, j, k - 1);
}
if (si(j + 1, k - 1, matriz) && matriz[j + 1][k - 1] == 'M') { // Suroeste
recursivo(matriz, j + 1, k - 1);
}
if (si(j + 1, k, matriz) && matriz[j + 1][k] == 'M') { // Sur
recursivo(matriz, j + 1, k);
}
if (si(j + 1, k + 1, matriz) && matriz[j + 1][k + 1] == 'M') { // Sueste
recursivo(matriz, j + 1, k + 1);
}
if (si(j, k + 1, matriz) && matriz[j][k + 1] == 'M') { // Este
recursivo(matriz, j, k + 1);
}
if (si(j - 1, k + 1, matriz) && matriz[j - 1][k + 1] == 'M') { // Noreste
recursivo(matriz, j - 1, k + 1);
}
}
private static boolean si(int j, int k, char[][] matriz) {
return j >= 0 && j < matriz.length && k >= 0 && k < matriz[0].length;
}
public static String[] readLine(java.io.BufferedReader reader) throws
java.io.IOException {
return reader.readLine().split(" ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment