分享一道TW的笔试题吧,该题目考查的是图的存储、深度优先遍历、最短路径等知识点。
图共有两种存储方式,第一种是邻接矩阵(二维数组),另外一种是邻接表(map+链表),
我采用的是邻接表的一种变种表示法,将链表用map替代了,为了方便通过顶点的值查找到
另一个顶点的路径。该题共有10个测试用例,目前只有9个测试用例是通过的,第10道题我
目前还没有找到解决方案,前5道题都是用同一种方式来遍历的,用前一个顶点的值为key在
邻接表查找下一个顶点的距离,如果找到就把距离累加起来,只要有一个顶点找不到就返回-1
代表路径不存在。第6、7题是一类题,要求找出符合不超过n站的路径数量,我先用深度优先
遍历出起始顶点到结束顶点所有可能的路径,再选出符合站数要求的路径数。第8,9题是计算
最短路径的,我用了Dijkstra算法计算出所有节点距离起始顶点最近的距离以及最近的顶点,
如果起始顶点和终止顶点不想听则直接返回距离,否则就要找出所有最近的顶点是原始起始顶点的
顶点,分别求得dist=当前节点离原始起始顶点的距离+shortestDist(当前顶点,原始起始顶点)
选择最小的dist即可。第10题我目前没有想到一种方法使得已经到达终止顶点还继续查找再次到达
终止顶点的路径,我目前仅仅求出了C-C有三种路径,题目中给出的那7种感觉是有规律的,像是那
三种路径的排列组合。

Problem one: Trains

 

The local commuter railroad services a number of towns in Kiwiland.  Because of monetary concerns, all of the tracks are 'one-way.'  That is, a route from Kaitaia to Invercargill does not imply the existence of a route from Invercargill to Kaitaia.  In fact, even if both of these routes do happen to exist, they are distinct and are not necessarily the same distance!

 

The purpose of this problem is to help the railroad provide its customers with information about the routes.  In particular, you will compute the distance along a certain route, the number of different routes between two towns, and the shortest route between two towns.

 

Input:  A directed graph where a node represents a town and an edge represents a route between two towns.  The weighting of the edge represents the distance between the two towns.  A given route will never appear more than once, and for a given route, the starting and ending town will not be the same town.

 

Output: For test input 1 through 5, if no such route exists, output 'NO SUCH ROUTE'.  Otherwise, follow the route as given; do not make any extra stops!  For example, the first problem means to start at city A, then travel directly to city B (a distance of 5), then directly to city C (a distance of 4).

  1. The distance of the route A-B-C.
  2. The distance of the route A-D.
  3. The distance of the route A-D-C.
  4. The distance of the route A-E-B-C-D.
  5. The distance of the route A-E-D.
  6. The number of trips starting at C and ending at C with a maximum of 3 stops.  In the sample data below, there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
  7. The number of trips starting at A and ending at C with exactly 4 stops.  In the sample data below, there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
  8. The length of the shortest route (in terms of distance to travel) from A to C.
  9. The length of the shortest route (in terms of distance to travel) from B to B.
  10. The number of different routes from C to C with a distance of less than 30.  In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.

 

Test Input:

For the test input, the towns are named using the first few letters of the alphabet from A to D.  A route between two towns (A to B) with a distance of 5 is represented as AB5.

Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7

Expected Output:

Output #1: 9

Output #2: 5

Output #3: 13

Output #4: 22

Output #5: NO SUCH ROUTE

Output #6: 2

Output #7: 3

Output #8: 9

Output #9: 9

Output #10: 7

package com.thoughtworks;

import java.util.*;


public class TrainsGraph {
    private Map<String, Map<String, Integer>> adj;//邻接表,存储各个顶点的关系
    private int v;//顶点个数
    private Set<String> vertexes;//所有的顶点集合

    /**
     * 构造方法初始化顶点之间的关系
     * @param str
     */
    public TrainsGraph(String str) {
        vertexes = new HashSet<>();
        adj = new HashMap<>();
        if (null == str || str.length() <=0 ){
            return;
        }
        String[] vertexLenths = str.split("、");
        for (String vertexLenth : vertexLenths) {
            if (vertexLenth.length() != 3) {
                continue;
            }
            String s = String.valueOf(vertexLenth.charAt(0));
            String t = String.valueOf(vertexLenth.charAt(1));
            int w = vertexLenth.charAt(2) - '0';
            Map<String, Integer> sEdgeMap = adj.get(s);
            if (null == sEdgeMap) {
                sEdgeMap = new HashMap<>();
                adj.put(s, sEdgeMap);
            }
            sEdgeMap.put(t, w);
            if (vertexes.add(s)) {
                v++;
            }
            if (vertexes.add(t)) {
                v++;
            }

        }



    }

    /**
     * 计算多个顶点组成的路径的距离,如果不存在路径返回-1
     * @param vertexes
     * @return
     */
    public int findDistOfPath(String[] vertexes) {
        if (null == vertexes || vertexes.length <= 0) {
            return -1;
        }
        String s = vertexes[0];
        int dist = 0;
        for (int i = 1; i < vertexes.length; i++) {
            String t = vertexes[i];
            Map<String, Integer> edgeMap = adj.get(s);
            if (null != edgeMap && edgeMap.containsKey(t)) {
                dist += edgeMap.get(t);
            } else {
                return -1;
            }
            s = t;
        }
        return dist;
    }

    /**
     * 通过Dijkstra算法求两个顶点最短距离
     * @param s
     * @param t
     * @return
     */
    public int findShortestDist(String s, String t) {
        Map<String, Vertex> parentMap = new HashMap<>(this.v);//存储离每个顶点最近的那个顶点和距离
        for (String vertex : vertexes) {
            parentMap.put(vertex, new Vertex(s, Integer.MAX_VALUE));
        }
        parentMap.put(s, null);
        Queue<Vertex> pqueue = new PriorityQueue<>(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Vertex v1 = (Vertex) o1;
                Vertex v2 = (Vertex) o2;
                return v1.dist - v2.dist;
            }
        });
        pqueue.add(new Vertex(s, 0));
        Set<String> visited = new HashSet<>(this.v);
        while (!pqueue.isEmpty()) {
            Vertex minVertex = pqueue.poll();
            if (!visited.add(minVertex.v)) {
                continue;
            }
            Map<String, Integer> edgeMap = adj.get(minVertex.v);
            for (Map.Entry<String, Integer> entry : edgeMap.entrySet()) {
                int dist = minVertex.dist + entry.getValue();
                if (null != parentMap.get(entry.getKey()) &&
                        dist < parentMap.get(entry.getKey()).dist) {//距离起始顶点的距离比之前的小 更新最短路径的前一个顶点为刚从优先级队列出队的顶点
                    parentMap.get(entry.getKey()).dist = dist;
                    parentMap.get(entry.getKey()).v = minVertex.v;
                }

                pqueue.add(new Vertex(entry.getKey(), dist));
            }
        }
        if (!s.equals(t)){
            return parentMap.get(t).dist;
        }else{
            return calculateDist(s , parentMap);
        }
    }

    /**
     * 计算起始和结束顶点相同的最短距离
     * 将问题分解为求起始顶点到与其距离最近的顶点之间的距离加上最近的那个顶点为起始顶点原来的起始顶点为结束顶点的最短距离
     * @param s
     * @param parentMap
     * @return
     */
    private int calculateDist(String s, Map<String, Vertex> parentMap) {
        int dist = Integer.MAX_VALUE;
        for (Map.Entry<String, Vertex> entry : parentMap.entrySet()) {
            if (entry.getValue() != null
                    && entry.getValue().v.equals(s)
                    && entry.getValue().dist < dist){
                String next = entry.getKey();//先找到距离目标顶点最近的顶点
                int curDist = entry.getValue().dist + findShortestDist(next , s);
                if (curDist < dist){
                    dist = curDist;
                }
            }
        }
        return dist;
    }

    /**
     * 找到两个顶点的所有路径列表
     * @param start
     * @param end
     * @return
     */
    public List<Object[]> getPathsOfTwoVertex(String start,String end){
        Stack<String> stack = new Stack<>();
        List<Object[]> paths = new LinkedList<>();
        Set<String> visited = new HashSet<>(this.v);
        dfsPath(start , start , end , null, stack , paths , visited);
        for(Object[] path : paths){
            printPath(path);
        }
        return paths;
    }

    /**
     * 找到小于最大距离的路径数量
     * @param start
     * @param end
     * @param maxDist
     * @return
     */
    public int countPathByDist(String start,String end , int maxDist){
        List<Object[]> paths = getPathsOfTwoVertex(start , end);
        int count = 0;
        if (null == paths || paths.size() <= 0){
            return count;
        }

        List<Integer> dists = new LinkedList<>();
        for(Object[] path : paths){
            List<String> list = new ArrayList<>(path.length);
            for (Object o : path){
                list.add(String.valueOf(o));
            }
            int dist = findDistOfPath(list.toArray(new String[0]));
            if (dist < maxDist){
                dists.add(dist);
                count++;
            }
        }
        return count;
    }

    /**
     * 找到不超过最大站数的路径数量
     * @param start
     * @param end
     * @param maxStop
     * @return
     */
    public int countPathByStop(String start,String end , int maxStop){
        List<Object[]> paths = getPathsOfTwoVertex(start , end);
        int count = 0;
        if (null == paths || paths.size() <= 0){
            return count;
        }

        for(Object[] path : paths){
            if (path.length <= maxStop){
                count++;
            }
        }
        return count;
    }

    /**
     * 通过深度优先搜索遍历图
     * @param start
     * @param index
     * @param end
     * @param prev
     * @param stack
     * @param paths 扫描到的所有路径列表
     * @param visited
     */
    public void dfsPath(String start,String index,String end ,String prev , Stack<String> stack, List<Object[]> paths,Set<String> visited) {
        stack.push(index);
        if (index.equals(end) && prev != null){
            paths.add(stack.toArray());
            stack.pop();
            System.out.println("找到终点"+index+",得到路径,往前回溯一位,查看节点"+index+"是否有其他路径");
        }else{
            Map<String, Integer> edgeMap = adj.get(index);
            System.out.println("依次搜索节点"+index+"的后置节点有"+ edgeMap);
            if (null != edgeMap && edgeMap.size() > 0) {
                for (Map.Entry<String, Integer> entry : edgeMap.entrySet()) {
                    System.out.println("搜索节点"+index+"的后置节点" + entry.getKey());
                    if (!stack.contains(entry.getKey()) || !visited.contains(entry.getKey())){
//                    if (!visited.contains(entry.getKey())){
                        dfsPath(start, entry.getKey(), end , index , stack , paths , visited);
                    }
                }

                visited.add(stack.pop());
                if (stack.size()>0){
                    System.out.println("节点"+index+"的后置节点搜索完毕,往前回溯一位,查看节点"+index+"处是否有其他路径");

                } else{
                    System.out.println("循环结束,已无其他路径!");

                }
            }
        }
    }

    /**
     * 打印路径
     * @param path
     */
    private void printPath(Object[] path) {
        StringBuilder sb = new StringBuilder();
        for (Object o : path) {
            sb.append(o);
        }
        System.out.println(sb);
    }

    /**
     * 顶点距离类保存目标顶点和起始顶点与目标顶点的距离
     */
    private class Vertex{
        public String v;
        public int dist;//distance of start vertex and v

        public Vertex(String v, int dist) {
            this.v = v;
            this.dist = dist;
        }
    }
}

 

测试用例:

package com.thoughtworks;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

public class TrainsGraphTest {
    private TrainsGraph graph;

    @Before
    public void initGraph() {
        //String str = "AB5、BC4、CD8、DC8、DE6、AD5、CE2、EB3、AE7";
        String str = readFromFile("src/main/resources/input.txt");
        graph = new TrainsGraph(str);
    }
    public String readFromFile(String fileName){
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileName));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }catch (FileNotFoundException e){
            System.out.println("readFromFile file not found");
        }catch (IOException e){
            System.out.println("readFromFile io exception,"+e.getMessage());
        }finally {
            if (reader != null){
                try {
                    reader.close();
                }catch (IOException e){
                    System.out.println("reader close exception,"+e.getMessage());
                }
            }
        }
        return sb.toString();
    }

    @Test
    public void test1() {
        String path = "A-B-C";
        int result = graph.findDistOfPath(path.split("-"));
        Assert.assertEquals(9, result);
    }

    @Test
    public void test2() {
        String path = "A-D";
        int result = graph.findDistOfPath(path.split("-"));
        Assert.assertEquals(5, result);
    }

    @Test
    public void test3() {
        String path = "A-D-C";
        int result = graph.findDistOfPath(path.split("-"));
        Assert.assertEquals(13, result);
    }

    @Test
    public void test4() {
        String path = "A-E-B-C-D";
        int result = graph.findDistOfPath(path.split("-"));
        Assert.assertEquals(22, result);
    }

    @Test
    public void test5() {
        String path = "A-E-D";
        int result = graph.findDistOfPath(path.split("-"));
        Assert.assertEquals(-1, result);
    }

    @Test
    public void test6() {
        int count = graph.countPathByStop("C", "C",4);
        System.out.println("test6:C->C,count:"+count);
        Assert.assertEquals(2, count);
    }

    @Test
    public void test7() {
        int count = graph.countPathByStop("A", "C" , 4);
        System.out.println("test6:A->C,count:"+count);
        Assert.assertEquals(3, count);
    }

    @Test
    public void test8() {
        int dist = graph.findShortestDist("A", "C");
        Assert.assertEquals(9, dist);
    }

    @Test
    public void test9() {
        int dist = graph.findShortestDist("B", "B");
        System.out.println("test9:B->B,count:"+dist);
        Assert.assertEquals(9, dist);
    }

    @Test
    public void test10() {
        int count = graph.countPathByDist("C", "C" , 30);
        System.out.println("test10:C->C,count:"+count);
        Assert.assertEquals(7, count);
    }

}

测试结果:

Problem one: Trains

相关文章: