Вы находитесь на странице: 1из 3

using System;

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

namespace DFS
{
public class Grafo<T>
{
public Grafo()
{
Vertices = new List<Vertice<T>>();
}

public List<Vertice<T>> Vertices { get; set; }


}
}

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

namespace DFS
{
public class Vertice<T>
{
public Vertice()
{
Vecinos = new List<Vertice<T>>();
}

public Vertice(T inicial)


: this()
{
Value = inicial;
}

public T Value { get; set; }


public bool Visitado { get; set; }

public List<Vertice<T>> Vecinos { get; set; }


}
}

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

namespace DFS
{
class Program
{
static Stack _pila = new Stack();
static Grafo<string> _grafo = new Grafo<string>();

static void DFS(Vertice<string> v)


{
var found = _grafo.Vertices.FirstOrDefault(ver => ver.Value == v.Value);
if (found != null && found.Visitado == false)
{
found.Visitado = true;
Console.WriteLine(found.Value);

// Tarea: Usar la pila en la logica


_pila.Push(found);

foreach (var vecino in found.Vecinos)


{
DFS(vecino);
}
}
}

static void Main(string[] args)


{
Console.WriteLine("Primer Ejemplo");
var v1 = new Vertice<string>();
v1.Value = "2";

var v2 = new Vertice<string>();


v2.Value = "0";

var v3 = new Vertice<string>();


v3.Value = "1";

var v4 = new Vertice<string>();


v4.Value = "3";

v1.Vecinos.Add(v2);
v2.Vecinos.Add(v1);

v3.Vecinos.Add(v1);
v1.Vecinos.Add(v3);

v3.Vecinos.Add(v2);
v2.Vecinos.Add(v3);

v1.Vecinos.Add(v4);
v4.Vecinos.Add(v1);

_grafo.Vertices.Add(v1);
_grafo.Vertices.Add(v2);
_grafo.Vertices.Add(v3);
_grafo.Vertices.Add(v4);

DFS(v1);

Console.ReadLine();
}
}
}

Вам также может понравиться