fork download
  1. import java.util.*;
  2.  
  3. class C {
  4.  
  5. public void run() {
  6. Scanner sc = new Scanner(System.in);
  7. while (sc.hasNext()) {
  8. int h = sc.nextInt();
  9. int w = sc.nextInt();
  10. int c = sc.nextInt();
  11. if ((h | w | c) == 0)
  12. return;
  13.  
  14. int[][] p = new int[h][w];
  15. for (int i = 0; i < h; i++)
  16. for (int j = 0; j < w; j++)
  17. p[i][j] = sc.nextInt();
  18.  
  19. int ans = 0;
  20. boolean[][][] mm = null;
  21. for (int t = 0; t < 1296; t++) {
  22. int[] cs = new int[5];
  23. for (int j = 0, k = t; j < 4; j++, k /= 6)
  24. cs[j] = k % 6 + 1;
  25. cs[4] = c;
  26. boolean[][][] map = new boolean[6][h][w];
  27. dfs(0, 0, p[0][0], p, map[0]);
  28. for (int k = 0; k < 5; k++)
  29. for (int i = 0; i < h; i++)
  30. for (int j = 0; j < w; j++)
  31. if (map[k][i][j])
  32. dfs(i, j, cs[k], p, map[k + 1]);
  33. int res = 0;
  34. for (int i = 0; i < h; i++)
  35. for (int j = 0; j < w; j++)
  36. if (map[5][i][j])
  37. res++;
  38. ans = Math.max(ans, res);
  39. if (ans == res)
  40. mm = map;
  41. }
  42. // for (int k = 0; k <= 5; k++)
  43. // for (int i = 0; i < h; i++) {
  44. // for (int j = 0; j < w; j++)
  45. // System.out.print((mm[k][i][j] ? "1" : "0") + " ");
  46. // System.out.println();
  47. // }
  48. System.out.println(ans);
  49. }
  50. }
  51.  
  52. static final int[] di = { 1, 0, -1, 0 };
  53. static final int[] dj = { 0, 1, 0, -1 };
  54.  
  55. private void dfs(int i, int j, int c, int[][] p, boolean[][] map) {
  56. map[i][j] = true;
  57. for (int d = 0; d < 4; d++) {
  58. int ni = i + di[d];
  59. int nj = j + dj[d];
  60. if (0 <= ni && ni < p.length && 0 <= nj && nj < p[0].length)
  61. if (p[ni][nj] == c && !map[ni][nj])
  62. dfs(ni, nj, c, p, map);
  63. }
  64. }
  65.  
  66. public static void main(String[] args) throws Exception {
  67. new C().run();
  68. }
  69. }
Success #stdin #stdout 0.16s 213824KB
stdin
3 5 5
1 6 3 2 5
2 5 4 6 1
1 2 4 1 5
4 5 6
1 5 6 1 2
1 4 6 3 2
1 5 2 3 2
1 1 2 3 2
1 1 5
1
1 8 6
1 2 3 4 5 1 2 3
8 1 1
1
2
3
4
5
1
2
3
8 8 6
5 2 5 2 6 5 4 2
4 2 2 2 5 2 2 2
4 4 4 2 5 2 2 2
6 4 5 2 2 2 6 6
6 6 5 5 2 2 6 6
6 2 5 4 2 2 6 6
2 4 4 4 6 2 2 6
2 2 2 5 5 2 2 2
8 8 2
3 3 5 4 1 6 2 3
2 3 6 4 3 6 2 2
4 1 6 6 6 4 4 4
2 5 3 6 3 6 3 5
3 1 3 4 1 5 6 3
1 6 6 3 5 1 5 3
2 4 2 2 2 6 5 3
4 1 3 6 1 5 5 4
0 0 0
stdout
10
18
1
5
6
64
33