using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 判断岛屿数量
     * @param grid char字符型二维数组
     * @return int整型
     */
    public int solve (List<List<char>> grid) {
        // write code here
        if (grid == null || grid.Count == 0)
            return 0;
        Dictionary<string, bool> kpvs = new Dictionary<string, bool>();
        for (int i = 0; i < grid.Count; i++)
            for (int j = 0; j < grid[i].Count; j++)
                kpvs.Add(i + "-" + j, false);
        int nDYCount = 0;
        for (int i = 0; i < grid.Count; i++) {
            for (int j = 0; j < grid[i].Count; j++) {
                if (kpvs[i + "-" + j] || grid[i][j] == '0')
                    continue;
                nDYCount++;
                DG(kpvs, grid.Count - 1, grid[i].Count - 1, i, j, grid);
            }
        }
        return nDYCount;
    }

    public static void DG(Dictionary<string, bool> kpvs, int nX, int nY, int nI,
                          int nJ, List<List<char>> grid) {
        if (nI < 0 || nI > nX || nJ < 0 || nJ > nY)
            return;
        if (grid[nI][nJ] == '0' || kpvs[nI + "-" + nJ])
            return;
        kpvs[nI + "-" + nJ] = true;
        //向上
        DG(kpvs, nX, nY, nI - 1, nJ, grid);
        //向下
        DG(kpvs, nX, nY, nI + 1, nJ, grid);
        //向左
        DG(kpvs, nX, nY, nI, nJ - 1, grid);
        //向右
        DG(kpvs, nX, nY, nI, nJ + 1, grid);
    }
}