从文件中读取节点,检查它们是否已连接

时间:2013-12-09 22:56:41

标签: java

在作业中我必须从文本文件中读取图形。节点用“\ t”分割。第一个进入第二个(有向图)。 我用hashmap和arraylist(邻接列表)来做这个,不确定邻接矩阵是否更容易。但我有一个问题。例如,如果我有

1   2
1   6
1   12
2   5
2   7

结果是:{1 = [2,6,12,5,7],2 = [2,6,12,5,7]} 而不是:{1 = [2,6,12],2 = [5,7]}。我不知道我必须检查(用钥匙)来解决它。 这是我的代码的一部分:

public static void main(String[] args) {
    try{
        BufferedReader inputFile = null;
        String line = new String();
        String[] par;
        int i,j;
        FileReader input = new FileReader("test.txt");
        BufferedReader bufRead = new BufferedReader(input);
        Map<Integer, ArrayList<Integer>> graph = new HashMap<Integer , ArrayList<Integer>>();
        ArrayList <Integer> edge = new ArrayList();
        while ((line = bufRead.readLine()) != null) {

                if (line.equals("")) {
                    continue;
                }
                par = line.split("\t");
                i = Integer.parseInt(par[0]);
                j = Integer.parseInt(par[1]);
                edge.add(j);
                graph.put(i, edge);
    }
    System.out.println(graph);

4 个答案:

答案 0 :(得分:0)

您将所有边缘存储在名为ArrayList的同一edge中。所以基本上你在HashMap graph

中为不同的密钥加载相同的值

您需要的是:

if(graph.containsKey(i)) {
  graph.get.add(j);
}

未经测试但应该向您提供要做的事情的要点。每次添加边缘之前,从图表中获取现有列表并添加边缘。

答案 1 :(得分:0)

您总是put相同的列表。您需要为不同的节点使用不同的列表(实例/对象),否则您只会修改(仅)现有的列表! e.g。

List<Integer> adjEdges = graph.get(i);
if(adjEdges == null)
{
   adjEdges = new ArrayList<Integer>();
}
adjEdges.add(j);
graph.put(i, adjEdges);

答案 2 :(得分:0)

你可以试试这个。

while ((line = bufRead.readLine()) != null) {

        if (line.equals("")) {
            continue;
        }
        par = line.split("\t");
        i = Integer.parseInt(par[0]);
        j = Integer.parseInt(par[1]);
        if(graph.containsKey(i)){        // if for the given key , an entry exists, fetch the array and add value to it.
            edge = graph.get(i);
            edge.add(j);
            graph.put(i, edge);

        }else{                           //if there is no entry for the key, create a new list and insert values into it.
            edge = new ArrayList();
            edge.add(j);
            graph.put(i, edge);
        }

    }

答案 3 :(得分:0)

我建议您在使用循环处理之前进行一些小比较

例如:

    int comp1;
        while ((line = bufRead.readLine()) != null) {

                        if (line.equals("")) {
                            continue;
                        }
                        par = line.split("\t");
                        i = Integer.parseInt(par[0]);
                        j = Integer.parseInt(par[1]);
                      if(comp1==null)
                     {
                     comp1=i;
                     }
              if(i!=comp1)
        {
         graph.put(i, edge);
        edge.clear()
        }

        edge.add(j);          
         comp1=i;
                }