题目描述

小哼通过秘密方法得到一张不完整的钓鱼岛航拍地图。钓鱼岛由一个主岛和一些附属岛屿组成,小哼决定去钓鱼岛探险。下面这个$10*10$的二维矩阵就是钓鱼岛的航拍地图。图中数字表示海拔,0表示海洋,$1~9$都表示陆地。小哼的飞机将会降落在$(6,8)$处,现在需要计算出小哼降落所在岛的面积(即有多少个格子)。注意此处我们把与小哼降落点上下左右相链接的陆地均视为同一岛屿。

输入

多组输入$n,m,x,y$

$n<=100$,$m<=100$,$0<x<=n$,$0<y<=m$

其后$n*m$个数字

输出

输出面积

样例输入

10 10 6 8
1 2 1 0 0 0 0 0 2 3
3 0 2 0 1 2 1 0 1 2
4 0 1 0 1 2 3 2 0 1
3 2 0 0 0 1 2 4 0 0
0 0 0 0 0 0 1 5 3 0
0 1 2 1 0 1 5 4 3 0
0 1 2 3 1 3 6 2 1 0
0 0 3 4 8 9 7 5 0 0
0 0 0 3 7 8 6 0 1 2
0 0 0 0 0 0 0 0 1 0

样例输出

38

题解

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
    static int[][] map;
    static int n,m;
    static int x;
    static int y;
    static Scanner cin=new Scanner(System.in);
    public static void main(String[] args) {
        init();
        solve();
    }
    static void init(){
        n=cin.nextInt();
        m=cin.nextInt();
        x=cin.nextInt();
        y=cin.nextInt();
        map=new int[n+1][m+1];
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                map[i][j]=cin.nextInt();
    }
    static void solve(){
        boolean[][] isfind=new boolean[n+1][m+1];
        int ans=0;
        LinkedList<Node> linkedList=new LinkedList<>();
        linkedList.add(new Node(x, y));
        isfind[x][y]=true;
        ++ans;
        int[][] dxdy=new int[][]{{-1,0},{0,-1},{1,0},{0,1}};
        while(linkedList.size()!=0){
            Node temp=linkedList.poll();
            for(int i=0;i<4;i++){
                x=temp.x+dxdy[i][0];//n行m列
                y=temp.y+dxdy[i][1];
                if(x<1||x>n||y<1||y>m||map[x][y]==0)
                    continue;
                if(!isfind[x][y]){
                    isfind[x][y]=true;
                    ++ans;
                    linkedList.add(new Node(x,y));
                }
            }
        }
        System.out.println(ans);
    }
}
class Node{
    int x;
    int y;
    Node(int x,int y){
        this.x=x;
        this.y=y;
    }
}