图的深度遍历和广度遍历(Java实现)

图的深度遍历和广度遍历(Java实现)

在下初涉Java, 为了体验一下Java的IO, 写了这段代码…
关于图的遍历大家一定很熟悉了,图的遍历体现了两种思想:
1.广度遍历: 队列的思想
2.深度遍历: 栈的思想

节点类

package test.io.graph.node;

public class TestGraphNode {

    public TestGraphNode(String key, String[] ns)
    {
        _key = key;
        _ns = ns;
    }

    public String getKey()
    {
        return _key;
    }

    public String[] getNeighbours()
    {
        return _ns;
    }

    public boolean hasNeighbours()
    {
        return _ns.length > 0;
    }

    public boolean isVisited()
    {
        return _isVisited;
    }

    public void setVisited(boolean visit)
    {
        _isVisited = visit;
    }

    private String _key;
    private String[] _ns;
    private boolean _isVisited;
}

图类

package test.io.graph;

import java.util.HashMap;

import test.io.graph.node.TestGraphNode;
import test.io.read.TestFileReader;

public class TestGraph {

    public TestGraph()
    {
        _nodes = new HashMap<String, TestGraphNode>();
    }

    public void initGraphWithConfig(String configPathName)
    {
        TestFileReader reader = new TestFileReader(configPathName);
        String graphConfig = reader.readAsString();

        graphConfig.trim(); 
        String[] nodeConfigs = graphConfig.split(";\n");
        for (int i = 0; i < nodeConfigs.length; ++i)
        {
            String v = nodeConfigs[i].substring(0, 1);
            int start = nodeConfigs[i].indexOf("(");
            int end = nodeConfigs[i].indexOf(")");
            String[] ns = nodeConfigs[i].substring(start + 1, end).split("-");
            TestGraphNode node = new TestGraphNode(v, ns);
            _nodes.put(v, node);
        }
    }

    public HashMap<String, TestGraphNode> getNodes()
    {
        return _nodes;
    }

    public TestGraphNode getNodeByKey(String key)
    {
        return _nodes.get(key);
    }

    public TestGraphNode getNodeByIndex(int index)
    {
        return (TestGraphNode)_nodes.values().toArray()[0];
    }

    private HashMap<String, TestGraphNode> _nodes;
}

遍历类

package test.io.graph.traverse;

import java.util.LinkedList;

import test.io.graph.TestGraph;
import test.io.graph.node.TestGraphNode;

public class TraverseTestGraph {

    public TraverseTestGraph()
    {

    }

    public String BFSTraverseGraph(TestGraph graph)
    {   
        String output = "";
        LinkedList<TestGraphNode> queue = new LinkedList<TestGraphNode>(); 
        queue.addLast(graph.getNodeByIndex(0));
        while (queue.size() != 0)
        {
            output += (queue.getFirst().getKey() + "->");
            queue.getFirst().setVisited(true);
            if (queue.getFirst().hasNeighbours())
            {
                for (int j = 0; j < queue.getFirst().getNeighbours().length; ++j)
                {
                    TestGraphNode n = graph.getNodeByKey(queue.getFirst().getNeighbours()[j]); 
                    if (!n.isVisited() && !(queue.contains(n)))
                    {
                        queue.addLast(n);
                    }
                }
            }
            queue.removeFirst();
        }
        output = output.substring(0, output.length() - 2);
        return output;
    }

    public String DFSTraverseGraph(TestGraph graph)
    {
        String output = "";
        TestGraphNode root = graph.getNodeByIndex(0);
        output = traverse(output, root, graph);
        output = output.substring(0, output.length() - 2);
        return output;
    }

    private String traverse(String output, TestGraphNode root, TestGraph graph)
    {   
        if (!root.isVisited())
        {
            output += (root.getKey() + "->");
            root.setVisited(true);
        }

        if (!root.hasNeighbours())
        {
            return output;
        }

        for (int i = 0; i < root.getNeighbours().length; ++i)
        {
            TestGraphNode node = graph.getNodeByKey(root.getNeighbours()[i]);
            if (!node.isVisited())
            {
                output = traverse(output, node, graph);
            }
        }
        return output;
    }
}

Writer类

package test.io.write;

import java.io.File;
import java.io.FileOutputStream;

public class TestFileWriter {

    public TestFileWriter(String pathname)
    {
        try
        {
            _os = new FileOutputStream(pathname);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public TestFileWriter(File file)
    {
        try
        {
            _os = new FileOutputStream(file);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void write(byte[] buffer)
    {
        try
        {
            _os.write(buffer);
            _os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private FileOutputStream _os;
}

Reader类

package test.io.read;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class TestFileReader {

    public TestFileReader(String pathname)
    {
        try
        {
            _is = new FileInputStream(pathname);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public TestFileReader(File file)
    {
        try
        {
            _is = new FileInputStream(file);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public String readAsString()
    {
        String ret = null;

        byte[] buffer = new byte[1000]; 
        try {
            int index = 0;
            int tempByte = -1;
            while ((tempByte = _is.read()) > 0)
            {
                buffer[index] = (byte)tempByte;
                index ++;
            }

            ret = new String(buffer, "utf-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ret;
    }

    private FileInputStream _is;
}

输入文件

A (B-C-D-E);
B (A-F);
C (A);
D (A);
E (A);
F (B)

广度遍历输出

A->B->C->D->E->F

深度遍历输出

A->B->F->C->D->E
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/freewill1010/article/details/48713603
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞