본문 바로가기
1일 1알고

[2021.12.02] 백준 1325 효율적인 해킹 DFS -진행중

by yeong. 2021. 12. 2.

방문처리 해주면서 막 손대다가 결과가 이상해짐ㄷㄷ

 

package week1;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main_1325_효율적인해킹_DFS {
	
	static int N, M;
	static List<Integer>[] computers;
	static int[] result;
	
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		N=sc.nextInt();
		M=sc.nextInt();
		
		computers=new ArrayList[N+1];
		result=new int[N+1];
		
		// 초기화
		for(int i=1;i<=N;i++) {
			computers[i]=new ArrayList<>();
		}
		
		// 관계 입력받기
		for(int i=0;i<M;i++) {
			int from=sc.nextInt();
			int to=sc.nextInt();
			
			computers[to].add(from);
		}
		
		int max=0; // 해킹할 수 있는 컴퓨터 최대값 저장할 변수
		for(int i=1;i<=N;i++) {
			countComputer(i); // i번에서 해킹할 수 있는 컴퓨터의 수
			
			if(max<result[i]) max=result[i]; // 해킹할 수 있는 컴퓨터의 수가 max보다 크다면 max에 저장한다
		}
		
		// 최대값이 여러개인 경우 다 출력해줌
		for(int i=1;i<=N;i++) {
			if(max==result[i]) System.out.print(i+" ");
		}
		
	}
	static int countComputer(int num) {
		System.out.println("countComputer");
		result[num]++; // 자기 자신 카운트
		
		for(int com: computers[num]) {
			if(result[com]==0) result[num]+=countComputer(com); // 컴퓨터의 수를 센 적이 없는 경우 새로 수를 세준다 
			else result[num]+=result[com]; // 이미 이 컴퓨터의 수를 센 적이 있는 경우, 그 값을 가지고 온다
		}
		
		return result[num]; 
	}
}