zoukankan      html  css  js  c++  java
  • Floyd最短路径算法

    代码:

    核心思想:a[i][j] = a[i][k] + a[k][j]

    import java.util.Scanner;
    
    public class Main {
    	int [][]ans = new int[101][101];
    	int nCrossRoads,mRoads;
    	void readNCrossRoadsAndMRoadsAndInit(int nCrossRoads,int mRoads){
    		this.nCrossRoads = nCrossRoads;
    		this.mRoads = mRoads;
    		for (int crossRoadsA = 1;crossRoadsA <= nCrossRoads;crossRoadsA ++) {    
    			for (int crossRoadsB = 1;crossRoadsB <= nCrossRoads;crossRoadsB ++) {
    				ans[crossRoadsA][crossRoadsB] = -1;
    			}
    			ans[crossRoadsA][crossRoadsA] = 0;  
    		} 
    	}
    	void initPerRoads(int crossRoadsA , int crossRoadsB , int costTime){
    		ans[crossRoadsA][crossRoadsB] = ans[crossRoadsB][crossRoadsA] = costTime; 
    	}
    	int floyd(){
    		for (int passedCrossRoads = 1;passedCrossRoads <= nCrossRoads;passedCrossRoads ++) {   
    			for (int crossRoadsA = 1;crossRoadsA <= nCrossRoads;crossRoadsA ++) {     
    				for (int crossRoadsB = 1;crossRoadsB <= nCrossRoads;crossRoadsB ++) {
    					if (ans[crossRoadsA][passedCrossRoads] == -1 || ans[passedCrossRoads][crossRoadsB] == -1) continue;
    					if ( ans[crossRoadsA][crossRoadsB] == -1 || ans[crossRoadsA][passedCrossRoads] + ans[passedCrossRoads][crossRoadsB] < ans[crossRoadsA][crossRoadsB])       
    						ans[crossRoadsA][crossRoadsB] = ans[crossRoadsA][passedCrossRoads] + ans[passedCrossRoads][crossRoadsB]; 
    				} 
    			}
    		}
    		return ans[1][nCrossRoads];
    	}
    	public static void main(String args[]){
    		Main f = new Main();
    		Scanner in = new Scanner(System.in);
    		int nCrossRoads,mRoads;
    
    		while (true) { 
    			nCrossRoads = in.nextInt();
    			mRoads =  in.nextInt();
    			if(nCrossRoads == 0 && mRoads == 0)	break;
    			f.readNCrossRoadsAndMRoadsAndInit(nCrossRoads, mRoads);
    			while(f.mRoads-- > 0){
    				int crossRoadsA , crossRoadsB , costTime; 
    				crossRoadsA = in.nextInt();
    				crossRoadsB = in.nextInt();
    				costTime = in.nextInt();
    				f.initPerRoads(crossRoadsA, crossRoadsB, costTime);
    			} 
    			int result = f.floyd();
    			System.out.println(result);
    		}
    		in.close();
    	}
    }
    

      

  • 相关阅读:
    Doing Homework 简单dp&&状态压缩
    嫖裤子序列
    王宁宁宁
    友军寻路法
    Viviani
    ccf 201909-3
    ccf 201909-5
    链式前向星
    ccf-201909-04
    ccf -201909-2
  • 原文地址:https://www.cnblogs.com/lchzls/p/7275333.html
Copyright © 2011-2022 走看看