爪哇國新遊記之二十五----圖及其遍曆尋找

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   io   資料   for   

代碼:

import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;// 頂點類class Vertex{    String name;// 名稱    boolean visited;// 是否已訪問過        public Vertex(String name){        this.name=name;        this.visited=false;    }}// 圖類public class Graph{    // 圖    private Vertex[] arr;// 頂點數組    private int[][] matrix;// 鄰接矩陣        // 建立圖的資料    private Set<String> vertexSet;// 包含不重複頂點的集合    private Map<String,String[]> connMap;// 包含串連的雜湊表        // 添加頂點之間的串連關係    public void addConn(String from,String[] toArr){        if(vertexSet==null){            vertexSet=new HashSet<String>();        }                vertexSet.add(from);        for(String to:toArr){            vertexSet.add(to);        }                if(connMap==null){            connMap=new LinkedHashMap<String,String[]>();        }                connMap.put(from, toArr);    }        // 建立圖(即其中的頂點數組和鄰接矩陣)    public void rebuildGraph(){        // 初始化頂點數組        List<String> ls=new ArrayList<String>();        ls.addAll(vertexSet);        Collections.sort(ls);                int size=ls.size();        arr=new Vertex[size];        for(int i=0;i<ls.size();i++){            arr[i]=new Vertex(ls.get(i));        }                // 初始化鄰接矩陣        matrix=new int[size][size];        for(String key:connMap.keySet()){            String[] values=connMap.get(key);                        for(String value:values){                int x=findVertexIndex(key);                int y=findVertexIndex(value);                                if(x!=-1 && y!=-1){                    matrix[x][y]=1;                    matrix[y][x]=1;                }            }        }    }        // 在頂點數組裡找頂點下標    private int findVertexIndex(String name){        for(int i=0;i<arr.length;i++){            if(name.equals(arr[i].name)){                return i;            }        }                return -1;    }        public void displayMatix(){        int n=arr.length;                System.out.print("  ");        for(int i=0;i<n;i++){            System.out.print(arr[i].name+",");        }        System.out.println();                System.out.print("-");        for(int i=0;i<n;i++){            System.out.print("--");        }        System.out.println();                for(int i=0;i<n;i++){            System.out.print(arr[i].name+":");                        for(int j=0;j<n;j++){                System.out.print(matrix[i][j]+",");            }                        System.out.println();        }    }        // 得到兩個點之間的路徑    public String getPath(String from,String to){        // 初始化        int fromIndex=findVertexIndex(from);        if(fromIndex==-1){            return "找不到頂點:"+from;        }                int toIndex=findVertexIndex(to);        if(toIndex==-1){            return "找不到頂點:"+to;        }                //  用於記住路徑的棧        Stack<Integer> stack=new Stack<Integer>(Integer.class,arr.length);                // 開始尋找        arr[fromIndex].visited=true;        stack.push(fromIndex);                while(stack.isEmpty()==false){            int j=getConnVertex(stack.peek());                        if(j==-1){                stack.pop();            }else{                arr[j].visited=true;                stack.push(j);                            if(arr[j].name.equals(to)){                    // 找到了                                        StringBuilder sb=new StringBuilder();                                        while(stack.isEmpty()==false){                        int index=stack.pop();                                                sb.insert(0, arr[index].name+"->");                    }                                        return sb.substring(0, sb.length()-2);                }            }        }                return "不可能從"+from+"到"+to;    }        // 取得串連未訪問過的頂點    private int getConnVertex(int i){        int n=arr.length;                for(int j=0;j<n;j++){            if(matrix[i][j]==1 && arr[j].visited==false){                return j;            }        }                return -1;    }        public static void main(String[] args){        Graph g=new Graph();                g.addConn("A", new String[]{"B","D"});        g.addConn("B", new String[]{"A","C"});        g.addConn("C", new String[]{"B","D","E"});        g.addConn("D", new String[]{"A","C"});        g.addConn("E", new String[]{"C"});        g.addConn("F", new String[]{"E","G"});        g.addConn("G", new String[]{"F"});        g.addConn("H", new String[]{"I","J"});        g.addConn("I", new String[]{"H","J"});        g.addConn("J", new String[]{"H","I"});                g.rebuildGraph();        g.displayMatix();        String path=g.getPath("A", "G");        System.out.println(path);                g.rebuildGraph();        path=g.getPath("A", "H");        System.out.println(path);                g.rebuildGraph();        path=g.getPath("J", "H");        System.out.println(path);                g.rebuildGraph();        path=g.getPath("F", "B");        System.out.println(path);    }}

輸出:

  A,B,C,D,E,F,G,H,I,J,---------------------A:0,1,0,1,0,0,0,0,0,0,B:1,0,1,0,0,0,0,0,0,0,C:0,1,0,1,1,0,0,0,0,0,D:1,0,1,0,0,0,0,0,0,0,E:0,0,1,0,0,1,0,0,0,0,F:0,0,0,0,1,0,1,0,0,0,G:0,0,0,0,0,1,0,0,0,0,H:0,0,0,0,0,0,0,0,1,1,I:0,0,0,0,0,0,0,1,0,1,J:0,0,0,0,0,0,0,1,1,0,A->B->C->E->F->G不可能從A到HJ->HF->E->C->B

 頂點:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.