Sfoglia il codice sorgente

(本代码AC)bfs宽搜

爱玲姐姐 5 anni fa
parent
commit
4c18d0b4f7
1 ha cambiato i file con 86 aggiunte e 0 eliminazioni
  1. 86 0
      H2.java

+ 86 - 0
H2.java

@@ -0,0 +1,86 @@
+package tuirngCup2019ahstuACM;
+
+import java.util.*;
+
+public class H2 {
+    private static class Result implements Comparable<Result>{
+        int s, c;
+        Result(int s, int c){
+            this.s = s;
+            this.c = c;
+        }
+
+        @Override
+        public int compareTo(Result o) {
+            if (s != o.s)return Integer.compare(o.s, s);//面积从大到小排序
+            return Integer.compare(c, o.c);//周长从大到小排序
+        }
+    }
+    private static boolean[][] book;//book作为标记数组
+    private static char[][] iceCream;
+    private static int[][] next = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
+    private static int s, c, n;
+    public static void main(String[] args) {
+        Scanner cin = new Scanner(System.in);
+        n = cin.nextInt();
+        iceCream = new char[n][n];
+        book = new boolean[n][n];
+        for (int i = 0; i < n; i++){
+            char[] row = cin.next().toCharArray();
+            for(int j = 0; j < n; j++){
+                iceCream[i][j] = row[j];
+            }
+        }
+        List<Result>res = new ArrayList<>();
+        for(int i = 0; i < n; i++){
+            for(int j = 0; j < n; j++){
+                if(iceCream[i][j] == '#' && !book[i][j]){
+                    s = 0; c = 0;
+                    bfs(i, j);
+                    res.add(new Result(s,c));
+                }
+            }
+        }
+        Collections.sort(res);
+        System.out.println(res.get(0).s + " " + res.get(0).c);
+    }
+    private static class Node{
+        int x, y;
+        Node(int x, int y){
+            this.x = x;
+            this.y = y;
+        }
+    }
+    private static void bfs(int x0, int y0) {
+        LinkedList<Node>queue = new LinkedList<>();
+        queue.push(new Node(x0, y0));
+        while(queue.size() > 0){
+            Node head = queue.pop();
+            if (!book[head.x][head.y]){
+                book[head.x][head.y] = true;
+                s++;
+                c += icecreamBoundary(head.x, head.y);
+            }
+            for(int i = 0; i < 4; i++){
+                int x = head.x + next[i][0];
+                int y = head.y + next[i][1];
+                if(x < 0 || y < 0 || x >= n || y >= n || iceCream[x][y] == '.' || book[x][y]){
+                    continue;
+                }
+                queue.push(new Node(x, y));
+            }
+        }
+    }
+
+    private static int icecreamBoundary(int x0, int y0) {
+        int ret = 0;
+        for(int i = 0; i < 4; i++){
+            int x = x0 + next[i][0];
+            int y = y0 + next[i][1];
+            if(x < 0 || y < 0 || x >= n || y >= n || iceCream[x][y] == '.'){
+                ret++;
+            }
+        }
+        return ret;
+    }
+}