Trang

Thứ Sáu, 31 tháng 12, 2010

3780. How Many Islands?

http://acm.tju.edu.cn/toj/showp3780.html

import java.io.*; public class Main { /** * @author hunglee */ static int w, h, a[][]; static int di[] = {-1, -1, -1, 0, 1, 1, 1, 0}; static int dj[] = {-1, 0, 1, 1, 1, 0, -1, -1}; public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); do { in.nextToken(); w = (int) in.nval; in.nextToken(); h = (int) in.nval; if (w == 0 && h == 0) break; a = new int[h + 2][w + 2]; for (int i = 1; i <= h; ++i) for (int j = 1; j <= w; ++j) { in.nextToken(); a[i][j] = (int) in.nval; } int res = 0; for (int i = 1; i <= h; ++i) for (int j = 1; j <= w; ++j) if (a[i][j] == 1) { ++res; visit(i, j); } System.out.println(res); } while (true); } private static void visit(int i, int j) { if (a[i][j] == 0) return; a[i][j] = 0; for (int k = 0; k < 8; ++k) visit(i + di[k], j + dj[k]); } }

Không có nhận xét nào:

Đăng nhận xét