import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[][] grid = new int[m][n]; int startIndexi = 0; int startIndexj = 0; for (int j = 0; j < m; j++) { int end = scanner.nextInt(); for (int i = 0; i < end; i++) { int tmp = scanner.nextInt(); if(tmp == 0){ startIndexi = j; startIndexj = i; } grid[j][tmp] = 1; } } Set<Integer> set = new HashSet<>(); for (int k = 0; k < n - 1; k++) { if(grid[startIndexi][k] == 1){ set.add(k); dfs(grid,startIndexi,k,set); } } System.out.println(set.size()); } public static void dfs(int[][] gird, int i, int j, Set<Integer> set){ if(i < 0 || i >= gird.length || j < 0 || j >= gird[0].length || gird[i][j] == 0) return; gird[i][j] = 0; set.add(j); //遇见1 就上下方向和左右方向遍历 for (int k = 0; k < gird[0].length; k++) { if(gird[i][k] == 1){ set.add(k); dfs(gird,i,k,set); } } for (int k = 0; k < gird.length; k++) { if(gird[k][j] == 1){ set.add(j); dfs(gird,k,j,set); } } } }
全部评论
(1) 回帖