如何使用输入文本文件创建一个邻接矩阵来表示有向加权图[java]? [英] how to create an adjacency matrix, using an input text file, to represent a directed weighted graph [java]?

查看:260
本文介绍了如何使用输入文本文件创建一个邻接矩阵来表示有向加权图[java]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何从输入文件创建邻接矩阵。输入文件应该表示节点的有向加权图。

I'm having a hard time figuring out how to create an adjacency matrix from an input file. The input file is supposed to represent a directed, weighted graph of nodes.

目的是创建一个可以进行迭代深度优先搜索的程序,但我真的停留在赋值的数据输入部分。

The purpose is to create a program that can do a iterative depth first search, but I'm really stuck on the data input part of the assignment.

输入文本文件应如下所示:

The input text file would supposedly look like the following:

每个节点由两行文字表示。例如,在最顶行,第一个'S'是节点的名称,第二个'S'表示它是一个起始节点,第三个'n'表示它是一个常规节点,而不是一个目标节点,这将由'g'表示。

each node is represented by two lines of text. For example the on the very top line, the first 'S' is the name of the node, the second 'S' indicates that it's a start node, the third 'n' indicates that it's a regular node, not a goal node, which would be indicated by a 'g'.

在第二行是连接到'S'的两个节点,第一个是'B',加权距离为1 ,第二个是加权距离为2的'E'。

On the second line are the two nodes connected to 'S' the first being 'B' with a weighted distance of 1, and the second being 'E' with a weighted distance of 2.

第三行应该是空白的,并重复模式。

The third line is supposed to be blank, and the pattern is repeated.

S S n                     
B 1 E 2            


B N n

C 2 F 3


C N n

D 2 GA 4

D N n

GA 1

E N n

B 1 F 3 H 6

F N n

I 3 GA
 3 C 1

GA N g

H N n

I 2 GB 2 F 1

I N n

GA 2 GB 2

GB N g

我真的坚持这个。我一直在使用缓冲读卡器扫描文件,但我一直想知道使用扫描仪是否会更容易。

I'm really stuck on this. I have been using buffered reader to scan in the file but I've been wondering if using Scanner would be easier.

我目前正在尝试使用具有名称的属性创建Node对象,并且可能使用某种链接列表链接到其他相邻的Node对象。我还考虑过使用一组节点对象,但我真的不确定如何表示哪些节点连接到哪些其他节点以及如何使用二维数组将其构建到邻接矩阵中。

I'm currently attempting to create Node objects with the attributes of having a name, and maybe a link to other adjacent Node objects using a linked list of some kind. I've also considered using an array of node objects but I'm really unsure how to represent which nodes connect to which other nodes and how to build that into an adjacency matrix using a two dimensional array.

任何建议都会非常感激,我是新手,所以如果我的问题对其他人没有学术重要性我会道歉

Any suggestions would be greatly appreciated, I'm a newbie so I apologize if my question is not of academic importance to others

编辑:我的代码是这样的:
public void actionPerformed(ActionEvent e)
{

my code is something like this: public void actionPerformed(ActionEvent e) {

    if(e.getSource() == openButton)
    {
        returnVal = fileChooser.showOpenDialog(null);

        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            selected_file = fileChooser.getSelectedFile();

            String file_name = fileChooser.getSelectedFile().getName();
            file_name = file_name.substring(0, file_name.indexOf('.'));

            try
            {
                BufferedWriter buff_writer = null;
                File newFile = new File("."+file_name+"_sorted.txt");           

                boolean verify_creation = newFile.createNewFile();
                //if (verify_creation)
                //  System.out.println("file created successfully");
                //else
                //  System.out.println("file already present in specified location");

                file_reader1 = new BufferedReader(new FileReader(selected_file));
                file_reader2 = new BufferedReader(new FileReader(selected_file));

                FileWriter file_writer = new FileWriter(newFile.getAbsoluteFile());
                buff_writer = new BufferedWriter(file_writer);

                //find the number of nodes in the file
                while( (currentLine = file_reader1.readLine()) != null)
                {
                    k++;
                    System.out.println("value of k: " + k);
                }


                nodeArray = new Node[k];

                while( (currentLine = file_reader2.readLine()) != null) 
                {   
                    //System.out.print(currentLine);

                    String[] var = currentLine.split(" ");


                    nodeArray[x] = new Node(var[0], var[1], var[2]);
                    nodeArray[x].setLink1(new Node(var[3], null, null));



                }

            buff_writer.close();
            file_writer.close();

            }   
            catch (Exception e1)
            {
                e1.printStackTrace();
            }       
        }
    }

编辑#2

我的节点对象如下所示:

my node object looks something like this:

public Node(String n, String t1, String t2)
{
    name = n;
    type1 = t1;
    type2 = t2;

    link1 = null;
    link2 = null;
    link3 = null;
    link4 = null;
    link5 = null;
    link6 = null;


推荐答案

事情是:你做想在这里使用二维数组。您想退后一步,设计/建模适合您正在使用的实际问题的类/数据结构。

Thing is: you do not want to use a two-dimensional array here. You want to step back and design/model a class/data structure that fits the "actual problem" you are working.

换句话说:你的问题是关于表示节点和边的图。所以,一些提示让你去..

In other words: your problem is about representing a graph of nodes and edges. So, some tips to get you going ..

让我们开始:

enum NodeType { START, GOAL, NORMAL ; }

public class Node {
  private final String name;

  public Node(String name) {
    this.name = name;

以上为您提供了区分不同类型节点的合理方法。然后我们从节点的表示开始。显然,它的名称是固定的 - 您不希望在创建节点后更改其名称。然后你有像

The above gives you a reasonable way to distinguish the different types of nodes. And then we start with the representation of a node. Obviously, its name is fixed - you dont want to change the name of a node after it was created. Then you have setters like

public void setType(NodeType type) ...

还有更多字段,

private final Map<Node, Integer> neighbors = new HashMap<>();

以及添加新邻居的方法:

and a method to add a new neighbor:

public void addNeighborNode(Node node, int weight) {
   neighbors.put(node, weight);

[记录:从理论上讲,你可以创建一个通过构造函数获取所有信息的类,避免需要有setter方法。这有一定的优势,但会使事情变得更复杂;我想......我在这里向你展示的内容已经很复杂了;-)]

[ for the record: theoretically, you could create a class that takes all infos via a constructor, avoiding the need of having setter methods. that has certain advantages, but makes things more complicated; and I guess ... what I am showing you here is complicated enough already ;-) ]

这里的整个想法 - 你将PARSING与你的表达方式分开/构建你的对象。当然,在某些时候你必须读取那些字符串,然后从它们构建节点对象。

The whole idea here - you separate the PARSING from the way how you represent/build your objects. Of course, at some point you have to read that strings, to then build node objects from them.

但你最好从上面的Node类开始,因为那样你可以构建图表...而无需解析文本文件:

But you better start with a Node class like above, because then you can build a graph ... without the need to parse a text file:

Node n1 = new Node("n1");
n1.setType(NodeType.START);

Node n2 = new Node("n2");
n2.setType(NodeType.GOAL);

n1.setNeighborNode(n2, 5);

换句话说:首先为图形构建一个漂亮的类模型。你可以像上面那样编写测试代码。当所有这些都奏效时;然后你编写读取输入文件的代码并将其转换为构建图形所需的方法调用!

In other words: first you build a nice "class model" for a graph. And you can write test code like above. And when all of that works; then you write the code that reads that input file and translates that into the method calls you need to build your graph!

长话短说:当然,解析那个文本文件很重要,但你应该专注于那个。相反:想想很多关于数据的类模型第一次。那就是你可以学到最多,并且在实验中获得最大的乐趣。拉入弦并将它们变成物体,这只是工作。先享受一些乐趣!

Long story short: of course, parsing that text file is important, but you should not focus on that. Instead: think a lot about the class model of your data first. That is were you can learn the most, and have the most fun in experimenting. Pulling in strings and turning them into objects, that is just "work". Have some fun first!

这篇关于如何使用输入文本文件创建一个邻接矩阵来表示有向加权图[java]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆