結果
問題 |
No.697 池の数はいくつか
|
ユーザー |
![]() |
提出日時 | 2019-08-20 21:20:09 |
言語 | Java (openjdk 23) |
結果 |
WA
|
実行時間 | - |
コード長 | 1,583 bytes |
コンパイル時間 | 2,178 ms |
コンパイル使用メモリ | 77,492 KB |
実行使用メモリ | 248,616 KB |
最終ジャッジ日時 | 2024-11-25 15:08:22 |
合計ジャッジ時間 | 49,496 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 WA * 2 |
other | AC * 10 WA * 21 TLE * 1 |
ソースコード
import java.util.*; public class Main { static int[] par; static int[] rank; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); int n = h * w; par = new int[n]; rank = new int[n]; init(n); int[][] a = new int[h][w]; for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { a[i][j] = sc.nextInt(); } } for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { if(a[i][j] == 1) { int p = i * w + j; if(i > 0) unite(p, p - w); if(i < h - 1) unite(p, p + w); if(j > 0) unite(p, p - 1); if(j < w - 1) unite(p, p + 1); } } } HashSet<Integer> set = new HashSet<Integer>(); for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { if(a[i][j] == 1) { set.add(find(i * w + j)); } } } System.out.println(set.size()); } static void init(int m) { for(int i = 0; i < m; i++) { par[i] = i; rank[i] = 1; } } static int find(int x) { if(par[x] == x) { return x; } else { return par[x] = find(par[x]); } } static void unite(int x, int y) { x = find(x); y = find(y); if(x != y) { if(rank[x] < rank[y]) { par[x] = y; } else { par[y] = x; if(rank[x] == rank[y]) rank[x]++; } } } static boolean same(int x, int y) { return find(x) == find(y); } }