CCF-通信网络(java实现)

参考:https://www.cnblogs.com/Lin-Yi/p/8568774.html

import java.util.List;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public Scanner sc;
	public int graph[][];
	public int visted[];
	 public List<Integer>[] list;
	public int root;
	public int count = 0;
	public int N,M;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main().run();
	}
	public void init() {
		sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		graph = new int[N+1][N+1];
		//visted = new int[N+1];
		list = new List[N+1];
		for(int i=1;i<=N;i++)
			list[i] = new ArrayList<>();
	}
	public void run() {
		init();
		for(int i=0;i<M;i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			list[a].add(b);
		}
		//对每个节点进行深度搜索
		for(int i=1;i<=N;i++) {
			root = i;
			visted = new int[N+1];
			dfs(i);
			/*for(int j=1;j<=N;j++)
				System.out.print(visted[j]+",");
			System.out.println();*/
		}
		for(int i=1;i<=N;i++) {
			for(int j=1;j<=N;j++) {
				if(graph[i][j] == 0)
					break;
				if(j==N)
					count++;
			}
		}
		System.out.println(count);
	}
	public void dfs(int cur) {
		graph[root][cur] = graph[cur][root] = 1;
		visted[cur] = 1;
		
		for(int i=0;i<list[cur].size();i++) {
			if(visted[list[cur].get(i)] == 0) {
				dfs(list[cur].get(i));
			}
		}
	}

}

 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页