H.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package tuirngCup2019ahstuACM;
  2. import java.util.*;
  3. import java.util.List;
  4. /*
  5. dfs代码会有运行错误,我觉得可能是因为数据量过大,引起栈溢出,导致运行错误
  6. */
  7. public class H {
  8. private static class Result implements Comparable<Result>{
  9. int s, c;
  10. Result(int s, int c){
  11. this.s = s;
  12. this.c = c;
  13. }
  14. @Override
  15. public int compareTo(Result o) {
  16. if (s != o.s)return Integer.compare(o.s, s);//面积从大到小排序
  17. return Integer.compare(c, o.c);//周长从大到小排序
  18. }
  19. }
  20. private static boolean[][] vis, book;//vis用来优化点不要重复访问,book作为dfs的递归过程的标记数组
  21. private static char[][] iceCream;
  22. private static int[][] next = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  23. private static int s, c, n;
  24. public static void main(String[] args) {
  25. Scanner cin = new Scanner(System.in);
  26. n = cin.nextInt();
  27. iceCream = new char[n][n];
  28. vis = new boolean[n][n];
  29. for (int i = 0; i < n; i++){
  30. char[] row = cin.next().toCharArray();
  31. for(int j = 0; j < n; j++){
  32. iceCream[i][j] = row[j];
  33. }
  34. }
  35. List<Result>res = new ArrayList<>();
  36. for(int i = 0; i < n; i++){
  37. for(int j = 0; j < n; j++){
  38. if(iceCream[i][j] == '#' && !vis[i][j]){
  39. book = new boolean[n][n];
  40. s = 0; c = 0;
  41. dfs(i, j);
  42. res.add(new Result(s,c));
  43. }
  44. }
  45. }
  46. Collections.sort(res);
  47. System.out.println(res.get(0).s + " " + res.get(0).c);
  48. }
  49. private static void dfs(int x0, int y0) {
  50. if (!vis[x0][y0]) {
  51. vis[x0][y0] = true;
  52. s++;
  53. c += icecreamBoundary(x0, y0);
  54. }
  55. for(int i = 0; i < 4; i++){
  56. int x = x0 + next[i][0];
  57. int y = y0 + next[i][1];
  58. if(x < 0 || y < 0 || x >= n || y >= n || iceCream[x][y] == '.' || book[x][y]){
  59. continue;
  60. }
  61. book[x][y] = true;
  62. dfs(x, y);
  63. book[x][y] = false;
  64. }
  65. }
  66. private static int icecreamBoundary(int x0, int y0) {
  67. int ret = 0;
  68. for(int i = 0; i < 4; i++){
  69. int x = x0 + next[i][0];
  70. int y = y0 + next[i][1];
  71. if(x < 0 || y < 0 || x >= n || y >= n || iceCream[x][y] == '.'){
  72. ret++;
  73. }
  74. }
  75. return ret;
  76. }
  77. }