[백준] 11403번 경로 찾기 (java, 플로이드 와샬)

728x90
반응형

www.acmicpc.net/problem/11403

 

11403번: 경로 찾기

가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 경로가 있는지 없는지 구하는 프로그램을 작성하시오.

www.acmicpc.net

import java.util.Scanner;

public class Main {
	static int n;
	static int[][] cost;
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		cost=new int[n][n];
		for (int i = 0; i <n; i++) {
			for (int j = 0; j < n; j++) {
				cost[i][j]=sc.nextInt();
			}
		}
		
		floyd();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(cost[i][j]+" ");
			}
			System.out.println();
		}
	}
	private static void floyd() {
		for (int k = 0; k < n; k++) {
			for (int s = 0; s < n; s++) {
//				if(k==s)continue;
				for (int e = 0; e < n; e++) {
//					if(k==e || s==e)continue;
					if(cost[s][k]==0 || cost[k][e]==0)continue;
					if(cost[s][e]==0) {
						cost[s][e]=1;
					}
				}
			} 
		}
		
	}
}
728x90
반응형
TAGS.

Comments