The submit say: Wrong Answer.
What is wrong on my code ?
Code: Select all
import java.util.Scanner;
public class Main {
private static char[][] grid;
private static int[] dx = { 0, -1, 0, 1 };
private static int[] dy = { -1, 0, 1, 0 };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = "";
int N = Integer.parseInt(sc.nextLine());
int map = 0;
while (N-- > 0) {
s = sc.nextLine();
String[] size = s.split("\\s");
int n = Integer.parseInt(size[0]);
int m = Integer.parseInt(size[1]);
grid = new char[n][m];
for (int i = 0; i < n; ++i) {
grid[i] = sc.nextLine().toCharArray();
}
char[] alph = letters();
int[] amm = new int[alph.length];
for (int i = 0; i < amm.length; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
if (grid[j][k] == alph[i]) {
dfs(j, k, alph[i], Character.toUpperCase(alph[i]));
amm[i]++;
}
}
}
}
sort(alph, amm);
System.out.print("World #" + (++map) + "\n");
for (int i = 0; i < amm.length; i++) {
System.out.print(alph[i] + ": " + amm[i] + "\n");
}
}
System.exit(0);
}
public static char[] letters() {
boolean[] aux = new boolean[26];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
aux[grid[i][j] - 'a'] = true;
}
}
int amm = 0;
for (boolean i : aux) {
if (i)
++amm;
}
char[] ret = new char[amm];
amm = 0;
for (int i = 0; i < 26; ++i) {
if (aux[i]) {
ret[amm++] = (char) (i + 'a');
}
}
return ret;
}
public static void dfs(int x, int y, char cur, char rep) {
if (grid[x][y] != cur)
return;
grid[x][y] = rep;
for (int i = 0; i < 4; i++) {
if (x + dx[i] >= 0 && y + dy[i] >= 0 && x + dx[i] < grid.length && y + dy[i] < grid[0].length && grid[x + dx[i]][y + dy[i]] == cur) {
dfs(x + dx[i], y + dy[i], cur, rep);
}
}
}
public static void sort(char[] alph, int[] amm) {
int n = alph.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (amm[j] < amm[j + 1]) {
char temp0 = alph[j + 1];
alph[j + 1] = alph[j];
alph[j] = temp0;
int temp1 = amm[j + 1];
amm[j + 1] = amm[j];
amm[j] = temp1;
}
}
}
}
}