Simple Java DFS
~~~java\n\nclass Solution {\n    int m, n;\n    int[] dx = new int[]{1,-1,0,0};\n    int[] dy = new int[]{0,0,1,-1};\n    \n    boolean[][] visited;\n    List> 
~~~java\n\nclass Solution {\n    int m, n;\n    int[] dx = new int[]{1,-1,0,0};\n    int[] dy = new int[]{0,0,1,-1};\n    \n    boolean[][] visited;\n    List<Set<Integer>> region;\n    List<Set<Integer>> frontier;\n    List<Integer> perimeter;\n    \n    public int containVirus(int[][] grid) {\n        m = grid.length;\n        n = grid[0].length;\n        int ans = 0;\n        \n        while (true) {\n            visited = new boolean[m][n];\n            region = new ArrayList<>();\n            frontier = new ArrayList<>();\n            perimeter = new ArrayList<>();\n            \n            for (int i = 0; i < m; i++) {\n                for (int j = 0; j < n; j++) {\n                    if (grid[i][j] == 1 && !visited[i][j]) {\n                        frontier.add(new HashSet<>());\n                        region.add(new HashSet<>());\n                        perimeter.add(0);\n                        dfs(grid, i, j);\n                    }\n                }\n            }\n        \n            if (region.size() == 0) return ans;\n            \n            int max = 0;\n            for (int i = 1; i < frontier.size(); i++) {\n                if (frontier.get(i).size() > frontier.get(max).size()) max = i;\n            }\n            ans += perimeter.get(max);\n            \n            for (int i = 0; i < region.size(); ++i) {\n                if (i == max) {\n                    for (int code: region.get(i))\n                        grid[code / n][code % n] = -1;\n                } else {\n                    for (int code: region.get(i)) {\n                        int r = code / n, c = code % n;\n                        for (int k = 0; k < 4; k++) {\n                            int nr = r + dx[k], nc = c + dy[k];\n                            if (nr >= 0 && nr < m && \n                                nc >= 0 && nc < n && \n                                grid[nr][nc] == 0)\n                                grid[nr][nc] = 1;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    private void dfs(int[][] grid, int x, int y) {\n        int len = region.size();\n        region.get(len-1).add(x * n + y);\n        visited[x][y] = true;\n        for (int k = 0; k < 4; k++) {\n            int nx = x + dx[k], ny = y + dy[k];\n            if (nx < 0 || ny < 0 || nx >= m || ny >= n) continue;\n            if (grid[nx][ny] == 1 && !visited[nx][ny]) dfs(grid, nx, ny);\n            else if (grid[nx][ny] == 0) {\n                frontier.get(len-1).add(nx * n + ny);\n                perimeter.set(len-1, perimeter.get(len-1)+1);\n            }\n        }\n    }\n}\n\n~~~
[]