結果

問題 No.697 池の数はいくつか
ユーザー chocoruskchocorusk
提出日時 2020-10-04 00:57:03
言語 Java21
(openjdk 21)
結果
AC  
実行時間 3,018 ms / 6,000 ms
コード長 1,367 bytes
コンパイル時間 2,592 ms
コンパイル使用メモリ 78,284 KB
実行使用メモリ 154,460 KB
最終ジャッジ日時 2024-04-25 20:54:45
合計ジャッジ時間 29,720 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 115 ms
54,032 KB
testcase_01 AC 115 ms
53,908 KB
testcase_02 AC 105 ms
52,880 KB
testcase_03 AC 113 ms
54,188 KB
testcase_04 AC 118 ms
54,048 KB
testcase_05 AC 118 ms
54,284 KB
testcase_06 AC 108 ms
53,144 KB
testcase_07 AC 115 ms
54,160 KB
testcase_08 AC 114 ms
54,320 KB
testcase_09 AC 119 ms
54,140 KB
testcase_10 AC 123 ms
54,376 KB
testcase_11 AC 118 ms
54,048 KB
testcase_12 AC 112 ms
53,068 KB
testcase_13 AC 123 ms
54,200 KB
testcase_14 AC 108 ms
53,184 KB
testcase_15 AC 113 ms
52,756 KB
testcase_16 AC 108 ms
53,508 KB
testcase_17 AC 109 ms
53,544 KB
testcase_18 AC 104 ms
52,996 KB
testcase_19 AC 104 ms
52,780 KB
testcase_20 AC 117 ms
54,188 KB
testcase_21 AC 123 ms
54,336 KB
testcase_22 AC 119 ms
54,168 KB
testcase_23 AC 113 ms
53,560 KB
testcase_24 AC 930 ms
73,192 KB
testcase_25 AC 905 ms
73,292 KB
testcase_26 AC 890 ms
73,148 KB
testcase_27 AC 936 ms
73,280 KB
testcase_28 AC 931 ms
73,320 KB
testcase_29 AC 2,857 ms
154,140 KB
testcase_30 AC 2,974 ms
154,088 KB
testcase_31 AC 2,956 ms
154,460 KB
testcase_32 AC 3,018 ms
153,816 KB
testcase_33 AC 2,955 ms
153,976 KB
testcase_34 AC 2,982 ms
154,036 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		PrintWriter out=new PrintWriter(System.out);
		int h=Integer.parseInt(scanner.next());
		int w=Integer.parseInt(scanner.next());
		int[][] a=new int[h][w];
		int cnt=0;
		for(int i=0; i<h; i++) {
			for(int j=0; j<w; j++) {
				a[i][j]=Integer.parseInt(scanner.next());
				if(a[i][j]==1) cnt++;
			}
		}
		UnionFind uf=new UnionFind(h*w);
		for(int i=0; i<h; i++) {
			for(int j=0; j<w; j++) {
				if(a[i][j]==0) continue;
				int x=i*w+j;
				if(i+1<h && a[i+1][j]==1) {
					if(uf.unite(x, (i+1)*w+j)) cnt--;
				}
				if(j+1<w && a[i][j+1]==1) {
					if(uf.unite(x,  i*w+j+1)) cnt--;
				}
			}
		}
		out.println(cnt);
		out.close();
		scanner.close();
	}
}
class UnionFind{
	int n;
	int[] par;
	int cmp;
	public UnionFind(int n) {
		this.n=n;
		this.par=new int[n];
		Arrays.fill(this.par, -1);
		this.cmp=n;
	}
	public int find(int x) {
		if(par[x]<0) return x;
		return par[x]=find(par[x]);
	}
	public boolean unite(int x, int y) {
		x=find(x);
		y=find(y);
		if(x==y) {
			return false;
		}
		cmp--;
		if(par[x]>par[y]) {
			int tmp=x;
			x=y;
			y=tmp;
		}
		par[x]+=par[y];
		par[y]=x;
		return true;
	}
	public boolean same(int x, int y) {
		return find(x)==find(y);
	}
}
0