Tarjan’s Algorithm - java
\n# Code\njava []\nclass Solution {\n    private int dfs(int[][] graph, int u, int parent, int time, int[] depth, int[] low, boolean[] infected, int[] count) {\
\n# Code\n```java []\nclass Solution {\n    private int dfs(int[][] graph, int u, int parent, int time, int[] depth, int[] low, boolean[] infected, int[] count) {\n        low[u] = depth[u] = time; // Set depth and low values\n        boolean isInfected = infected[u];\n        int size = 1; // Size of the component rooted at u\n\n        for (int v = 0; v < graph[u].length; v++) {\n            if (graph[u][v] == 1) { // If u is connected to v\n                if (depth[v] == 0) { // v is not visited\n                    int subtreeSize = dfs(graph, v, u, time + 1, depth, low, infected, count);\n                    if (subtreeSize == 0) { // If v is infected\n                        isInfected = true;\n                    } else {\n                        size += subtreeSize; // Increase size of the component\n                    }\n                    if (low[v] >= depth[u]) { // If v can\'t reach back to u or its ancestors\n                        count[u] += subtreeSize; // Count size for u\n                    }\n                    low[u] = Math.min(low[u], low[v]); // Update low value\n                } else if (v != parent) { // Update low value for back edge\n                    low[u] = Math.min(low[u], depth[v]);\n                }\n            }\n        }\n        return isInfected ? 0 : size; // Return size if not infected, otherwise 0\n    }\n\n    public int minMalwareSpread(int[][] graph, int[] initial) {\n        int n = graph.length;\n        int ans = initial[0], maxCount = 0;\n        boolean[] infected = new boolean[n];\n\n        // Mark all initially infected nodes\n        for (int u : initial) infected[u] = true;\n\n        int[] depth = new int[n], low = new int[n], count = new int[n];\n\n        // Perform DFS for each initially infected node\n        for (int u : initial) {\n            if (depth[u] == 0) { // If u is not visited\n                dfs(graph, u, -1, 1, depth, low, infected, count);\n            }\n            // Check for the optimal node to remove\n            if (count[u] > maxCount || (count[u] == maxCount && u < ans)) {\n                maxCount = count[u]; // Update maximum count\n                ans = u; // Update answer node\n            }\n        }\n        return ans; // Return the best node to remove\n    }\n}\n\n```
['Java']