广度优先遍历

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorldSeek
{
public class SceneNode
{
public int SceneID { get; set; }
public List<int> AroundScene { get; set; }
public SceneNode Parnet { get; set; }
public bool Visited { get; set; }

public SceneNode()
{
AroundScene = new List<int>();
Visited = false;
Parnet = null;
}
}

public class WorldScenePeek
{
private static WorldScenePeek _worldScenePeek;

private static List<SceneNode> _nodes;

private WorldScenePeek()
{
_nodes = new List<SceneNode>
{
new SceneNode{SceneID = 101,AroundScene = new List<int>{102,104,105,107,109}},
new SceneNode{SceneID = 102,AroundScene = new List<int>{120,101}},
new SceneNode{SceneID = 104,AroundScene = new List<int>{101}},
new SceneNode{SceneID = 105,AroundScene = new List<int>{101}},
new SceneNode{SceneID = 107,AroundScene = new List<int>{101}},
new SceneNode{SceneID = 109,AroundScene = new List<int>{112,110,115,101}},
new SceneNode{SceneID = 110,AroundScene = new List<int>{109}},
new SceneNode{SceneID = 112,AroundScene = new List<int>{109}},
new SceneNode{SceneID = 115,AroundScene = new List<int>{109}},
new SceneNode{SceneID = 120,AroundScene = new List<int>{102}},
};
}

public static WorldScenePeek Instance
{

get { return _worldScenePeek ?? (_worldScenePeek = new WorldScenePeek()); }
}

private SceneNode getNode(int id)
{
return _nodes.FirstOrDefault(node => node.SceneID == id);
}

public List<int> seek(int beginId,int endId)
{
var startNode = getNode(beginId);
var endNode = getNode(endId);
if(startNode == null || endNode == null)
return null;
if(startNode.SceneID == endNode.SceneID)
return new List<int>{beginId};

//先将所有节点置为未访问,并且没有父节点
foreach(var node in _nodes)
{
node.Visited = false;
node.Parnet = null;
}

var path = new List<int>();
var success = Find(startNode, endNode);
if(success)
{
var tmpNode = endNode;
while(tmpNode != null)
{
path.Add(tmpNode.SceneID);
tmpNode = tmpNode.Parnet;
}
return path;
}
return null;
}

//采用图的广度优先遍历
private bool Find(SceneNode curNode,SceneNode endNode)
{
curNode.Visited = true;
var testList = new List<SceneNode>();

readyTestList(testList, curNode);
while(testList.Count > 0)
{
var readyList = new List<SceneNode>();
foreach(var node in testList)
{
if(node.SceneID == endNode.SceneID)
{
return true;
}
readyTestList(readyList, node);
}
testList = readyList;
}
return false;
}

private void readyTestList(List<SceneNode> testList,SceneNode node)
{
foreach(var nid in node.AroundScene)
{
var subNode = getNode(nid);
if(subNode!=null && !subNode.Visited)
{
testList.Add(subNode);
subNode.Visited = true;
subNode.Parnet = node;
}
}
}
}
}

  

原文地址:https://www.cnblogs.com/nywd/p/2359692.html