去哪儿-机票业务-宇文玥-楚乔题-40%AC
发布于 2017-10-11 11:12 2240 次浏览 0 赞 最后一次编辑是 2017-10-11 16:18 来自 试题交流  
import java.util.*;
public class T1 {
/**
 * BFS广度优先算法
 * 最后AC 40%,请大神帮助提点
 * 写得不好,请多担待
 * ----------------------
 */

     public static void main(String[] args){
         Scanner in = Scanner(System.);
         n = in.nextInt();
         m = in.nextInt();

         Map<String, ArrayList<String>> map = HashMap<>();

         String depart = in.next();
         String destination = in.next();

         for (i=0; i<m; i++) {
             String from = in.next();
             String to = in.next();
             
             if (!map.containsKey(from))
                 map.put(from, new ArrayList<String>());
             
             //经提示后添加以下三行: 需要记录往返路线
             if(!map.containsKey(to)) //记录回程路线
                 map.put(to, new ArrayList<String>());
             map.get(to).add(from);
             
             map.get(from).add(to);

         }

         Queue<String> queue = LinkedList<>();
         Set<String> visited = HashSet<>();
         queue.add(depart);
         visited.add(depart);
         step = 0;

         while (!queue.isEmpty()) {
             size = queue.size();
             step++;
              
             while (size > 0) {
                 size--;
                 String curr = queue.poll();
                 // visited.add(curr);
                 ArrayList<String> des = map.get(curr);
                 if (des != null) {
                     (String str : des) {
                         if (str.equals(destination) || str == destination) {
                             System..println(step);
                             return;
                         } else {
                             if (visited.add(str)) {
                                 queue.add(str);
                             }
                         }
                     }
                 }
                 else
                    continue;
             }

         }
         System..println("DISCONNECTED");
     }
}


3 条回复

测试用例答案貌似是

2 3 4 4 DISCONNEXTED

直接输出4也是40%


2017-10-11 11:29
1

题目:

共有m条国内航线,航线都是可往返的

你只写了

map.get(from).add(to);

貌似是这个原因

2017-10-11 11:47
acmcoderJuXPaz9T 回复 coder_O58ZPW8B

一下明白错在哪里了…感谢 : )

2017-10-11 16:09
添加回复
回到顶部