public void MissingTarget() { Node <string> a = new Node <string>("A"); Node <string> b = new Node <string>("B"); Node <string> c = new Node <string>("C"); Node <string> d = new Node <string>("D"); Node <string> e = new Node <string>("E"); a.Dependencies.Add(b); a.Dependencies.Add(c); a.Dependencies.Add(d); a.Dependencies.Add(e); List <Node <string> > list = new List <Node <string> >(); list.Add(a); list.Add(b); list.Add(c); list.Add(d); list.Add(e); DepthFirstSearch <string> sort = new DepthFirstSearch <string>(list); Stack <Node <string> > results = sort.GetDependencyPath("F"); Assert.AreEqual(results.Count, 0); }
public void SimplePath() { Node <string> a = new Node <string>("A"); Node <string> b = new Node <string>("B"); Node <string> c = new Node <string>("C"); Node <string> d = new Node <string>("D"); a.Dependencies.Add(b); b.Dependencies.Add(c); c.Dependencies.Add(d); List <Node <string> > list = new List <Node <string> >(); list.Add(a); list.Add(b); list.Add(c); list.Add(d); DepthFirstSearch <string> sort = new DepthFirstSearch <string>(list); Stack <Node <string> > results = sort.GetDependencyPath(a.Identity); Assert.AreEqual(results.Count, 4); Assert.IsTrue(d.Identity.Equals(results.Pop().Identity)); Assert.IsTrue(c.Identity.Equals(results.Pop().Identity)); Assert.IsTrue(b.Identity.Equals(results.Pop().Identity)); Assert.IsTrue(a.Identity.Equals(results.Pop().Identity)); }
public void TraverseTest() { string[] lines = File.ReadAllLines("SPTestGraph.txt"); int n = int.Parse(lines[0].Split(' ')[0]); int m = int.Parse(lines[0].Split(' ')[1]); double pathCost = double.Parse(lines[lines.Length - 1]); DirectedGraph graph = new DirectedGraph(new MatrixRepresentation(n)); for (int i = 0; i < m; i++) { string[] tokens = lines[i + 1].Split(' '); int from = int.Parse(tokens[0]); int to = int.Parse(tokens[1]); double cost = double.Parse(tokens[2]); graph.AddEdge(new Edge(from, to, cost)); } List <int> order = new List <int>(); DepthFirstSearch dfs = new DepthFirstSearch(); dfs.Initialize(graph, 0); int curNode; while (dfs.Traverse(out curNode)) { order.Add(curNode); } if (order.Count != 6) { Assert.Fail(); } }
public void BestBookOpeningTest() { var subset = new List <string> { @"\MB,B", @"\MB,B", @"\MB,W", @"\MB,W", @"\MC,W", @"\MC,W", @"\MD,B", @"\MD,B", @"\MD,W", }; var gameStateStats = new Dictionary <short, PlayStats> { { 0, new PlayStats(subset.Count, subset, @"\M", 'B') }, { 1, new PlayStats(subset.Count, subset, @"\M", 'C') }, { 2, new PlayStats(subset.Count, subset, @"\M", 'D') }, }; var depthFirstSearch = new DepthFirstSearch(); var bestIndexBlack = depthFirstSearch.BestBookPlay(gameStateStats, 0); Assert.AreEqual((short)2, bestIndexBlack); var bestIndexWhite = depthFirstSearch.BestBookPlay(gameStateStats, 1); Assert.AreEqual((short)1, bestIndexWhite); }
public void Solve(string mazename, string algorithm) { if (!(m_controller as MyController).mazes.ContainsKey(mazename)) { (m_controller as MyController).M_view.Output("maze name does not exists"); return; } SearchableMaze3d sm = new SearchableMaze3d(((m_controller as MyController).mazes[mazename] as Maze3d)); if (algorithm.ToLower().Equals("bfs")) { BreadthFirstSearch bs = new BreadthFirstSearch(); Solution bssol = bs.Solve(sm); (m_controller as MyController).bfssolutions.Add(mazename, bssol); (m_controller as MyController).M_view.Output("BFS solution for " + mazename + " is ready"); } else if (algorithm.ToLower().Equals("dfs")) { DepthFirstSearch ds = new DepthFirstSearch(); Solution dssol = ds.Solve(sm); (m_controller as MyController).dfssolutions.Add(mazename, dssol); (m_controller as MyController).M_view.Output("DFS solution for " + mazename + " is ready"); } else { (m_controller as MyController).M_view.Output("Wrong searching algorithm"); } }
public void HarderStillPath() { Node <string> a = new Node <string>("A"); Node <string> b = new Node <string>("B"); Node <string> c = new Node <string>("C"); Node <string> d = new Node <string>("D"); Node <string> e = new Node <string>("E"); a.Dependencies.Add(b); a.Dependencies.Add(c); a.Dependencies.Add(d); a.Dependencies.Add(e); List <Node <string> > list = new List <Node <string> >(); list.Add(a); list.Add(b); list.Add(c); list.Add(d); list.Add(e); DepthFirstSearch <string> sort = new DepthFirstSearch <string>(list); Stack <Node <string> > results = sort.GetDependencyPath(a.Identity); foreach (Node <string> node in results) { Console.WriteLine(node.Identity); } Assert.AreEqual(results.Count, 5); }
public void Should_TraverseAllNodesInDepthFirstOrder_When_Called() { // [arrange] var node0 = new Node("0"); var node1 = new Node("1"); var node2 = new Node("2"); var node3 = new Node("3"); var node4 = new Node("4"); var node5 = new Node("5"); node0.Children = new Node[] { node1, node4, node5 }; node1.Children = new Node[] { node3, node4 }; node3.Children = new Node[] { node1, node2, node4 }; var graph = new Node[] { node0, node1, node2, node3, node4, node5 }; var underTest = new DepthFirstSearch(); // [act] underTest.TraverseAndPrint(node0); // [assert] Assert.Equal("0", underTest.DfsOrderedList[0]); Assert.Equal("1", underTest.DfsOrderedList[1]); Assert.Equal("3", underTest.DfsOrderedList[2]); Assert.Equal("2", underTest.DfsOrderedList[3]); Assert.Equal("4", underTest.DfsOrderedList[4]); Assert.Equal("5", underTest.DfsOrderedList[5]); }
public void Find_FromVertexDisconnectedFromToVertex_EmptyPath() { var graph = AdjacencyListFactory.CreateDirected(); graph.AddVertex("a") .AddEdge("b") .AddEdge("c") .AddEdge("g"); graph.AddVertex("c") .AddEdge("d") .AddEdge("e") .AddEdge("f"); graph.AddVertex("f") .AddEdge("g"); //path of graph not connected with others graph.AddVertex("m") .AddEdge("n"); graph.AddVertex("n") .AddEdge("o"); var search = new DepthFirstSearch(graph); var result = search.BuildPath("a").GetPathString("n"); result.Should().Be(""); }
public void TestWDFSLoop() { var graph = new WeightedDirectedGraph <string>(); var v1 = "One"; var v2 = "Two"; var v3 = "Three"; var v4 = "Four"; var v5 = "Five"; graph.AddVertex(v1); graph.AddVertex(v2); graph.AddVertex(v3); graph.AddVertex(v4); graph.AddVertex(v5); graph.AddEdge(v1, v2, 3); graph.AddEdge(v1, v4, 5); graph.AddEdge(v1, v3, 20); graph.AddEdge(v2, v4, 21); graph.AddEdge(v3, v1, 1); graph.AddEdge(v3, v5, 4); graph.AddEdge(v5, v1, 6); var expected = new LinkedList <string>(); expected.AddLast(v1); expected.AddLast(v3); expected.AddLast(v5); var actual = DepthFirstSearch <string> .Search(graph, v1, v5); Assert.AreEqual(expected, actual); }
private Dictionary <Vertex, int> RetrieveDFSVertexFinishTime() { DepthFirstSearch search = new DepthFirstSearch(_graph); Dictionary <Vertex, VertexVisitData> visitResult = search.VisitGraph(); return(visitResult.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.FinishTime)); }
private static void Main(string[] args) { // the maze size 100x100 int col = 100; int row = 100; // create maze with DFSMazeGenerator DFSMazeGenerator generator = new DFSMazeGenerator(); Maze maze = generator.Generate(col, row); // print the maze Console.Write(maze.ToString()); // adapt the maze and solve it with BFS ISearchable <Position> adapter = new MazeAdapter(maze); ISearcher <Position> bfsSearcher = new BestFirstSearch <Position>(); bfsSearcher.Search(adapter); int bfsNumOfStases = bfsSearcher.GetNumberOfNodesEvaluated(); // solve the maze with DFS ISearcher <Position> dfsSearcher = new DepthFirstSearch <Position>(); dfsSearcher.Search(adapter); int dfsNumOfStases = dfsSearcher.GetNumberOfNodesEvaluated(); // print the num of evalueted nodes for BFS and DFS Console.WriteLine("number of BFS states:" + bfsNumOfStases); Console.WriteLine("number of DFS states:" + dfsNumOfStases); Console.Read(); }
public void TwoNodesGraphWithCircularDependency() { var sut = new DepthFirstSearch(); var graph = new[] { new GraphVertex <int> { Value = 1, AdjacentVertices = new System.Collections.Generic.List <int> { 1 } }, new GraphVertex <int> { Value = 2, AdjacentVertices = new System.Collections.Generic.List <int> { 0 } }, }; Assert.Collection(sut.Traverse(graph), arg => Assert.Equal(1, arg), arg => Assert.Equal(2, arg)); }
/* * // Para copiar el puzle con el que este trabajando otro resolutor... raro * public TankPuzzleSolver(TankPuzzleSolver copyBoard) : this(copyBoard.getPuzle()) { * * } */ // A ver si esto tiene que estar aquí o puede ser otra cosa (en el propio TankPuzzleManager) public List <Operator> Solve(TankPuzzle setup, TankPuzzleSolver.Strategy strategy) { // Construimos el problema a partir del puzle. //Pieza a pieza (el puzle tal cual será el initialSetup -lo mismo debería sacar el array-) //Aquí construimos el problema en base al puzle actual (la CONFIGURACIÓN del puzle actual), que no me gusta como es porque es el puzle con unas pocas cosas por encima!!! El dominio de problema no es un objeto Problem problem = new Problem(setup, oFunction, rFunction, goalTest); //Me molaría más que el problema no sea el solver, sino el puzle... pero bueno, quizá sea PROBLEM lo que debería llamarse el solver //public Problem(Object initialSetup, OperatorsFunction operatorsFunction, ResultFunction resultFunction, GoalTest goalTest) // AQUÍ CREARÍAMOS LA ESTRATEGIA, EL TIPO DE BÚSQUEDA, pidiéndole que use búsqueda de coste uniforme por ejemplo. Y lo llamamos Search search = null; switch (strategy) { case Strategy.BFS: search = new BreadthFirstSearch(); break; //por defecto te crea un GraphSearch, no hay que meterle nada case Strategy.DFS: search = new DepthFirstSearch(new GraphSearch()); break; // NO ENTIENDO PORQUE ESTE CONSTRUCTOR NO TE HACE NADA POR DEFECTO, Y SOY YO QUE LE ESTOY METIENDO UN GRAPHSEARCH // ... } List <Operator> operators = search.Search(problem); metrics = search.GetMetrics(); return(operators); // Deberíamos devolver también las métricas, seguramente }
public static void TestCaseBook() { // 1. Create a graph CGraph mgraph = CGraph.CreateGraph(); CGraphNode u = mgraph.CreateGraphNode <CGraphNode>("u"); CGraphNode v = mgraph.CreateGraphNode <CGraphNode>("v"); CGraphNode w = mgraph.CreateGraphNode <CGraphNode>("w"); CGraphNode x = mgraph.CreateGraphNode <CGraphNode>("x"); CGraphNode y = mgraph.CreateGraphNode <CGraphNode>("y"); CGraphNode z = mgraph.CreateGraphNode <CGraphNode>("z"); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(u, v, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(u, x, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x, v, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(v, y, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(y, x, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(w, y, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(w, z, GraphType.GT_DIRECTED); mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(z, z, GraphType.GT_DIRECTED); DepthFirstSearch dfs = new DepthFirstSearch(mgraph); dfs.Run(); DepthFirstSearchQueryInfo info = new DepthFirstSearchQueryInfo(mgraph, dfs); CIt_GraphNodes it = new CIt_GraphNodes(mgraph); for (it.Begin(); !it.End(); it.Next()) { Console.WriteLine("Node {0}: arrival ({1}) - departure ({2})", it.M_CurrentItem.M_Label, info.Arrival(it.M_CurrentItem), info.Departure(it.M_CurrentItem)); } }
public bool DepthFirstSearch(T source, T destination) { var src = GetNode(source); var des = GetNode(destination); return(DepthFirstSearch <T> .HasPath(src, des)); }
public void Small_maze_FindPath_test() { var start = new Point(9, 3); var end = new Point(1, 5); var maze = @" %%%%%%%%%%%%%%%%%%%% %--------------%---% %-%%-%%-%%-%%-%%-%-% %--------P-------%-% %%%%%%%%%%%%%%%%%%-% %.-----------------% %%%%%%%%%%%%%%%%%%%%"; var getCell = GetCell(maze); var getNeighbours = GetNeighbours(getCell); var result = DepthFirstSearch.FindPath(start, getNeighbours, point => point == end).ToArray(); for (var i = 0; i < result.Length - 1; i++) { var twoPoints = result.Skip(i).Take(2).ToArray(); var point1 = twoPoints[0]; var point2 = twoPoints[1]; var distance = Math.Abs(point1.X - point2.X) + Math.Abs(point1.Y - point2.Y); Assert.That(distance, Is.EqualTo(1)); } Assert.That(result.Last(), Is.EqualTo(end)); }
public void DfsCountTest() { var g = GraphSample(); var dfs = new DepthFirstSearch(g, 0); Assert.Equal(6, dfs.Count); }
public void GetPathTo_OnValidParameters_ReturnsExpectedResult(int fromVertexIndex, int toVertexIndex, IEnumerable <int> expectedPath) { var dfs = new DepthFirstSearch <int>(_graph, fromVertexIndex); var actualResult = dfs.GetPathTo(toVertexIndex); Assert.Equal(expectedPath, actualResult); }
private void btnDepthFirstSearch_Click(object sender, EventArgs e) //DEPTH FIRST SEARCH BUTTON { //Declaring a new instance of DepthFirstSearch and displaying properties to the Windows Form DepthFirstSearch dfsSort = new DepthFirstSearch(); richTextBox2.AppendText(dfsSort.TimeComplexity + "\n"); richTextBox2.AppendText(dfsSort.SpaceComplexity + "\n"); //Displaying the Advantages and Disadvantages of DepthFirstSearch to the Windows Form StringBuilder qs = new StringBuilder(); qs.Append("DEPTH FIRST SEARCH: \nThe Depth First Search (DFS) is an algorithm for traversing or searching tree or graph data " + "structures which uses the idea of backtracking. It explores all the nodes by going forward if possible or uses backtracking. " + "It can be implemented using a stack.\n\n -DFS starts the traversal from the root node and visits nodes as far as " + "possible from the root node (i.e., depth wise).\n -Usually implemented using a stack data structure.\n " + "-Generally requires less memory than BFS.\n -Not optimal for finding the shortest distance.\n -Used for topological sorting, " + "solving problems that require graph backtracking, detecting cycles in a graph, finding paths between two nodes, etc."); richTextBox1.AppendText(qs.ToString()); //Displaying extra notes from a rich text file in the bin using (StreamReader Reader = new StreamReader(@"C:\Users\Clayt\source\repos\CSC205\CSC205_StudyProject\CSC205_StudyProject\bin\DepthFirstSearch.rtf")) { while (!Reader.EndOfStream) { richTextBox5.AppendText(Reader.ReadLine()); } } }
public void HasPathTo_OnValidParameters_ReturnsExpectedResult(int fromVertexIndex, int toVertexIndex, bool expectedResult) { var dfs = new DepthFirstSearch <int>(_graph, fromVertexIndex); var actualResult = dfs.HasPathTo(toVertexIndex); Assert.Equal(expectedResult, actualResult); }
public void AssertCanSearch() { IGraph graph = new GraphAdjMatrix(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); graph.AddEdge(0, 1); graph.AddEdge(1, 2); graph.AddEdge(2, 3); graph.AddEdge(3, 4); graph.AddEdge(4, 5); graph.AddEdge(5, 6); graph.AddEdge(5, 8); graph.AddEdge(6, 7); graph.AddEdge(7, 8); graph.AddEdge(8, 5); graph.AddEdge(0, 9); graph.AddEdge(9, 10); graph.AddEdge(10, 11); graph.AddEdge(11, 12); var dfs = new DepthFirstSearch(graph); var result = dfs.CanFind(0, 12); Assert.IsTrue(result); var direction = dfs.PathToGoal(); Assert.AreEqual(12, direction[4]); Assert.AreEqual(11, direction[3]); Assert.AreEqual(10, direction[2]); Assert.AreEqual(9, direction[1]); Assert.AreEqual(0, direction[0]); }
public void AssertCanNotSearch() { IGraph graph = new GraphAdjMatrix(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); graph.AddEdge(0, 1); graph.AddEdge(1, 2); graph.AddEdge(2, 3); graph.AddEdge(3, 4); graph.AddEdge(4, 5); graph.AddEdge(5, 6); graph.AddEdge(5, 8); graph.AddEdge(6, 7); graph.AddEdge(7, 8); graph.AddEdge(8, 5); graph.AddEdge(0, 9); graph.AddEdge(9, 10); graph.AddEdge(10, 11); var dfs = new DepthFirstSearch(graph); var result = dfs.CanFind(0, 12); Assert.IsFalse(result); }
public void TestDFSFail() { var graph = new DirectedGraph <string>(); var v1 = "One"; var v2 = "Two"; var v3 = "Three"; var v4 = "Four"; var v5 = "Five"; graph.AddVertex(v1); graph.AddVertex(v2); graph.AddVertex(v3); graph.AddVertex(v4); graph.AddVertex(v5); graph.AddEdge(v1, v2); graph.AddEdge(v2, v4); graph.AddEdge(v3, v5); var expected = new LinkedList <string>(); var actual = DepthFirstSearch <string> .Search(graph, v1, v5); Assert.AreEqual(expected, actual); }
/// <summary> /// The Solve /// </summary> /// <param name="baseGraph">The baseGraph<see cref="BaseGraph"/></param> /// <returns>The <see cref="List{Component}"/></returns> List <Component> IConnectedComponentsSolver.Solve(BaseGraph baseGraph) { List <Component> components = new List <Component>(); Component component = null; DepthFirstSearch depthFirstSearch = new DepthFirstSearch(); int n = baseGraph.Nodes; int curNode = -1; bool[] visited = new bool[n]; for (int i = 0; i < n; i++) { if (!visited[i]) { depthFirstSearch.Initialize(baseGraph, i); component = new Component(); components.Add(component); } while (depthFirstSearch.Traverse(out curNode)) { visited[curNode] = true; component.Nodes.Add(curNode); } } return(components); }
public static IList <string> Answer(IList <string> inputs) { var chars = new[] { ' ' }; var line0 = inputs[0].Split(chars); var verticeCount = int.Parse(line0[0]); var edgeCount = int.Parse(line0[1]); var xs = Enumerable.Range(1, edgeCount) .Select(i => { var items = inputs[i].Trim().Split(chars, StringSplitOptions.RemoveEmptyEntries); return(new { Left = GetIndex(items[0]), Right = GetIndex(items[1]) }); }); var graph = new GraphAdjacentyList(verticeCount); foreach (var x in xs) { graph.AddUndirectedEdge(x.Left, x.Right); } //Console.WriteLine(graph.ToPrettyString()); var dsf = new DepthFirstSearch(graph); dsf.Search(); //Console.WriteLine(dsf.ToPrettyString()); return(new[] { dsf.ConnectedComponents.ToString() }); }
public void Test() { // orientovaný ohodnocený. var graph1 = new DirectedWeightedGraph(false); for (int i = 'a'; i < 'h'; i++) { graph1.AddVertex(Convert.ToString(Convert.ToChar(i))); } graph1.AddEdge("a", "b", 1); graph1.AddEdge("b", "c", 2); graph1.AddEdge("c", "d", 3); graph1.AddEdge("d", "e", -4); graph1.AddEdge("f", "c", 5); graph1.AddEdge("a", "g", 600); graph1.AddEdge("b", "f", 0); graph1.AddEdge("b", "e", 7); DepthFirstSearch <DirectedWeightedGraph> .Search(graph1, "a"); Assert.AreEqual(0, graph1.GetVertex("a").distance); Assert.AreEqual(1, graph1.GetVertex("b").distance); Assert.AreEqual(2, graph1.GetVertex("c").distance); Assert.AreEqual(3, graph1.GetVertex("d").distance); Assert.AreEqual(4, graph1.GetVertex("e").distance); Assert.AreEqual(2, graph1.GetVertex("f").distance); Assert.AreEqual(1, graph1.GetVertex("g").distance); }
// Resuelve el puzle, en su configuración actual, utilizando la estrategia introducida como parámetro public List <Operator> Solve(SlidingPuzzle initialSetup, SlidingPuzzleSolver.Strategy strategy) { // Construimos el problema a partir del puzle que nos llega, que actúa como configuración inicial // No se indica función de coste de paso, con lo que se utilizará la que viene por defecto Problem problem = new Problem(initialSetup, aoFunction, tModel, gTest); // Se crea la búsqueda según la estrategia escogida Search search = null; switch (strategy) { case Strategy.BFS: search = new BreadthFirstSearch(); break; // Por defecto se usa un GraphSearch case Strategy.DFS: search = new DepthFirstSearch(new GraphSearch()); break; // Por defecto se usa un GraphSearch // ... hay cabida para otras estrategias } // Se realiza la búsqueda sobre el problema List <Operator> operators = search.Search(problem); // Al terminar, se guardan las métricas resultantes metrics = search.GetMetrics(); return(operators); }
static void Main(string[] args) { var tree = new BinaryNode <char>('A'); var leftNode = new BinaryNode <char>('B'); var rightNode = new BinaryNode <char>('S'); leftNode.LeftNode = new BinaryNode <char>('C'); leftNode.RightNode = new BinaryNode <char>('D'); tree.LeftNode = leftNode; rightNode.LeftNode = new BinaryNode <char>('H'); rightNode.LeftNode.LeftNode = new BinaryNode <char>('G'); rightNode.LeftNode.RightNode = new BinaryNode <char>('I'); rightNode.RightNode = new BinaryNode <char>('J'); rightNode.RightNode.LeftNode = new BinaryNode <char>('M'); tree.RightNode = rightNode; var DFS = new DepthFirstSearch <char>(); DFS.Explore(tree); var BFS = new BreadthFirstSearch <char>(); BFS.Explore(tree); Console.ReadKey(); }
/// <summary> /// Solves the specified maze. /// </summary> /// <param name="name">The name.</param> /// <param name="algorithmNumber">The algorithm number.</param> /// <returns>Solution.</returns> public Solution solve(string name, int algorithmNumber) { var maze = DictionaryOfMazes[name]; var searchableMaze = new SearchableMaze(maze); if (DictionaryOfMazesAndSolutions.ContainsKey(searchableMaze)) { return(DictionaryOfMazesAndSolutions[searchableMaze]); } Solution solution; ISearcher searchAlgorithm = null; switch (algorithmNumber) { case 0: searchAlgorithm = new BestFirstSearch <PointState>(); break; case 1: searchAlgorithm = new DepthFirstSearch <PointState>(); break; } solution = searchAlgorithm.search(searchableMaze); EvaluateNodes = searchAlgorithm.getNumberOfNodesEvaluated(); DictionaryOfMazesAndSolutions.Add(searchableMaze, solution); return(solution); }
public IDepthFirstSearch <ExchangeRate> Create(IEnumerable <ExchangeRate> rates) { IAdjacencyList <ExchangeRate> adjlist = _AdjacencyListFactory.CreateList(rates); IDepthFirstSearch <ExchangeRate> DFS = new DepthFirstSearch(adjlist); return(DFS); }
public void TraverseGraph(string graphText, string expectedTraversal) { var graph = graphText.ToGraph<string, object>(); string traversal = ""; var algo = new DepthFirstSearch<string, object>(); algo.Run(graph["start"], x => { traversal += x.Id + ","; }); traversal = traversal.TrimEnd(new[] { ',' }); Assert.That(traversal, Is.EqualTo(expectedTraversal), "Search path was not correct."); }
private void outputResults(Graph<Node, Edge> graph, int src, int tgt) { SysDbg.Write("\t"); DFS dfs = new DFS(graph, src, tgt); if (dfs.TargetFound) { SysDbg.Write("DFS from " + src + " to " + tgt + ": "); List<int> path; dfs.PathToTarget(out path); foreach (int node in path) SysDbg.Write(node + " "); SysDbg.WriteLine(""); } else SysDbg.WriteLine("DFS search could not find " + tgt + " from " + src + "!"); }
/// <summary> /// Renders the configuration specified. /// </summary> /// <returns></returns> public bool Render() { LogUtilities.LogSettings(config,log); nodeList = new List<Node<string>>(); Boolean returnCode = true; if (File.Exists(config.ConfigFile)) { log.LogMessage("Reading in configuration file..."); RenderConfig renderConfig = ReadConfigurationFile(); if (renderConfig != null) { //HACK We should be using a deep copy so that all this becomes "variableStack = dependencyStack.Clone();" //Get the list of nodes nodeList = GenerateNodeList(renderConfig, log); if (SearchForNodeByIdentity(nodeList, config.Configuration) == null) { throw new ApplicationException("Could not find Configuration : " + config.Configuration); } List<Node<string>> n2 = GenerateNodeList(renderConfig, log); //Generate the dependency path DepthFirstSearch<string> dfs = new DepthFirstSearch<string>(nodeList); DepthFirstSearch<string> dfs2 = new DepthFirstSearch<string>(n2); dependencyStack = dfs.GetDependencyPath(config.Configuration); //HACK Need to write a deep copy Queue Clone to get rid of this... variableStack = dfs2.GetDependencyPath(config.Configuration); } if (Directory.Exists(config.OutputDirectory)) { if (config.DeleteOutputDirectory) { log.LogMessage("Deleting and recreating output directory..."); Directory.Delete(config.OutputDirectory, true); Directory.CreateDirectory(config.OutputDirectory); } } else { log.LogMessage("Creating output directory..."); Directory.CreateDirectory(config.OutputDirectory); } //Create a queue of mods to run and a queue of EnvironmentVariables to implement //Variables have to be put in place before the mods... log.LogMessage("Building dependency queue..."); Queue<Configuration> configsToRun = CreateConfigProcessQueue(renderConfig, dependencyStack); //HACK This is ugly, needs a deep copy here.... Queue<Configuration> envQueue = CreateConfigProcessQueue(renderConfig, variableStack); while (envQueue.Count > 0) { Configuration varConfig = envQueue.Dequeue(); //First, we need to get all the Variables and create them. foreach (EnvironmentVariable variable in varConfig.EnvironmentVariables) { Environment.SetEnvironmentVariable(variable.variable, variable.Value); } } while (configsToRun.Count > 0) { Configuration currentConfig = configsToRun.Dequeue(); log.LogMessage(MessageImportance.High, "Running modification: " + currentConfig.Name); if (currentConfig.TargetFiles != null) { if (!currentConfig.Apply(config, log)) { log.LogError("Failed to apply configuration: " + currentConfig.Name); returnCode = false; } } } } else { log.LogError("Could not find configuration file: " + config.ConfigFile); returnCode = false; } //Let 'em know if (returnCode) { log.LogMessage(MessageImportance.High, "Configuration rendered!"); } else { log.LogError("Failed to render configuration."); } return returnCode; }
public StronglyConnectedComponents(IDirectedGraph g) { graph = g; dfs = new DepthFirstSearch(g); dfs.VisitingVertex += Dfs_VisitingVertex; }
void Start() { tileArray = new Tile[Width,Height]; GameObject.FindGameObjectWithTag("Player").transform.position = new Vector3(Width / 2 * TileSize, Height / 2 * TileSize, 0); DepthFirstSearch dpFirstSearch = new DepthFirstSearch(); mapArray = dpFirstSearch.Generate(new Vector2(Width, Height), new Vector2(Width / 2, Height / 2), Random.Range(0,100000)); for (int x = 0; x < mapArray.GetLength(0); x++) { for (int y = 0; y < mapArray.GetLength(1); y++) { if (mapArray[x, y] == 1) { GameObject obj = Instantiate(tile, new Vector3(x * TileSize, y * TileSize, 0), Quaternion.identity) as GameObject; tileArray[x,y] = obj.GetComponent<Tile>(); if(x == Width / 2 && y == Height / 2) { obj.GetComponent<Tile>().NotShrinking = true; } } } } int diamons = 0; while (diamons < MaxDiamonds) { int x = Random.Range(3, Width - 3); int y = Random.Range(3, Height - 3); if (mapArray[x,y] == 1 && !tileArray[x,y].NotShrinking) { //Instantiate(diamond, new Vector3(x*TileSize, y*TileSize), Quaternion.identity); gem = Instantiate (diamond, new Vector3(x*TileSize, y*TileSize), Quaternion.identity) as Gem; gem.transform.SetParent(tileArray[x, y].transform); diamons++; } } int extraWall = 0; while (extraWall < MaxExtraWalls) { int x = Random.Range(2, Width - 2); int y = Random.Range(2, Height - 2); if (mapArray[x, y] == 0) { Instantiate(tile, new Vector3(x * TileSize, y * TileSize), Quaternion.identity); extraWall++; } } int enemies = 0; while (enemies < MaxEnemies) { int x = Random.Range(3, Width - 3); int y = Random.Range(3, Height - 3); Instantiate(enemy, new Vector3(x * TileSize, y * TileSize), Quaternion.identity) ; enemies++; } }