Exemple #1
0
        // -> Retorna uma lista de cut-vertices para o grafo this
        public List <Vertice> GetCutVertices()
        {
            List <Vertice> cutVertices = new List <Vertice>();

            this.Vertices.ForEach(v =>
            {
                Grafo auxGrafo     = Grafo.CriarGrafo(this.ArquivoGerador);
                Vertice auxVertice = auxGrafo.GetVertice(v.Id);

                auxGrafo.RemoverVertice(auxVertice);

                if (!auxGrafo.IsConexo())
                {
                    cutVertices.Add(v);
                }
            });

            return(cutVertices);
        }
Exemple #2
0
        // -> Insere ua aresta composta por dois vértices e o peso
        public void InserirAresta(Vertice de, Vertice para, int peso)
        {
            // -> busca se os vértices já estão presentes no grafo
            Vertice auxDe = this.Vertices.Find(v => v.Id == de.Id);

            if (auxDe is null)
            {
                this.InserirVertice(de);
                auxDe = de;
            }

            // -> busca se os vértices já estão presentes no grafo
            Vertice auxPara = this.Vertices.Find(v => v.Id == para.Id);

            if (auxPara is null)
            {
                this.InserirVertice(para);
                auxPara = para;
            }

            auxDe.AdicionarAdjacente(auxPara, peso);
        }
Exemple #3
0
        public static void RelatorioNaoDirecionado()
        {
            string nomeArquivo = "completo3.txt";

            string[] linhas = File.ReadLines("./files/ArquivosNaoDirigidos/" + nomeArquivo).ToArray();

            Grafo grafo = Grafo.CriarGrafo(linhas);

            Grafo grafoP = Grafo.CriarGrafo(linhas);
            Grafo grafoK = Grafo.CriarGrafo(linhas);

            Vertice v1 = grafo.GetVertice("1");
            Vertice v2 = grafo.GetVertice("2");

            Vertice vk = grafoP.GetVertice("1");
            Vertice vp = grafoK.GetVertice("1");

            // -> PARA GRAFOS NÃO DIRECIONADO

            Console.WriteLine("{0} e {1} são adjacente: {2}", v1.Id, v2.Id, grafo.IsAdjacente(v1, v2));
            Console.WriteLine("O vértice {0} tem grau: {1}", v1.Id, grafo.GetGrau(v1));
            Console.WriteLine("O vértice {0} é isolado: {1}", v1.Id, grafo.IsIsolado(v1));
            Console.WriteLine("O vértice {0} é pendente: {1}", v1.Id, grafo.IsPendente(v1));

            Console.WriteLine("O grafo é regular: " + grafo.IsRegular());
            Console.WriteLine("O grafo é nulo: " + grafo.IsNulo());
            Console.WriteLine("O grafo é completo: " + grafo.IsCompleto());
            Console.WriteLine("O grafo é conexo: " + grafo.IsConexo());
            Console.WriteLine("O grafo é euleriano: " + grafo.IsEuleriano());
            Console.WriteLine("O grafo é unicursal: " + grafo.IsUnicursal());

            Console.WriteLine("A quantidade de cut-vértices é: " + grafo.GetCutVertices().Count);
            grafo.GetCutVertices().ForEach(v => Console.WriteLine(v.Id));

            grafoP.GetAGMPrim(vp);
            System.Console.WriteLine();
            System.Console.WriteLine();
            grafoK.GetAGMKruskal(vk);
        }
 // -> Método para classificar as arestas
 public void ClassificarAresta(Vertice v, Aresta a)
 {
     if (v.Cor == "Cinza" && a.Vertice.Cor == "Branco")
     {
         a.TipoAresta = "Árvore";
     }
     else if ((v.Cor == "Cinza" || v.Cor == "Preto") && a.Vertice.Cor == "Cinza")
     {
         a.TipoAresta = "Retorno";
     }
     else if ((v.Cor == "Cinza" || v.Cor == "Preto") && a.Vertice.Cor == "Preto")
     {
         if (v.TempoEntrada > a.Vertice.TempoEntrada)
         {
             a.TipoAresta = "Cruzamento";
         }
         else
         {
             a.TipoAresta = "Avanço";
         }
     }
 }
Exemple #5
0
 // -> Obtem os pessos de arestas dos vértices v1 e v2
 public int[] GetPesos(Vertice v1, Vertice v2)
 {
     return(v1.GetPesos(v2));
 }
Exemple #6
0
 // -> Retorna se um vértice é pendente
 public bool IsPendente(Vertice v)
 {
     return(v.IsPendente());
 }
Exemple #7
0
 // -> Retorna se um vértice é isolado
 public bool IsIsolado(Vertice v)
 {
     return(v.IsIsolado());
 }
Exemple #8
0
 // -> Obtem o grau de saida de um vertice em um grafo
 // direcionado ou o grau normal para um grafo não direcionado
 public int GetGrau(Vertice v)
 {
     return(v.GetGrau());
 }
Exemple #9
0
 // -> Verifica se há adjacência entr dois vértices
 public bool IsAdjacente(Vertice v1, Vertice v2)
 {
     return(v1.IsAdjacente(v2));
 }
Exemple #10
0
        // -> Retorna Arvore Geradora Mínima usando o algoritmo de Prim
        public void GetAGM(Grafo grafo, Vertice v1)
        {
            List <ArestaK> arestasK = new List <ArestaK>();
            Grafo          grafoAGM = new Grafo();

            int    pesoMinimo  = v1.ListaAdjacencia.Min(a => a.Peso);
            Aresta adjV1Minimo = v1.ListaAdjacencia.Find(a => a.Peso == pesoMinimo);

            ArestaK arestaInicial = new ArestaK(v1, adjV1Minimo.Vertice, adjV1Minimo.Peso, adjV1Minimo.Id);

            // -> Agrupando todas as arestas do grafo
            grafo.Vertices.ForEach(v =>
            {
                v.ListaAdjacencia.ForEach(a =>
                {
                    // -> Não adiciona arestas de mesmo Id
                    if (!arestasK.Any(a1 => a1.Id == a.Id))
                    {
                        arestasK.Add(new ArestaK(v, a.Vertice, a.Peso, a.Id));
                    }
                });
            });

            // -> Ordena elementos a partir do peso
            arestasK.Sort((a1, a2) => a1.Peso - a2.Peso);

            arestasK.RemoveAll(a => a.Id == arestaInicial.Id);
            arestasK.Insert(0, arestaInicial);


            // -> Inserir aresta inicial
            grafoAGM.InserirAresta(arestaInicial.V1, arestaInicial.V2, arestaInicial.Peso);
            Aresta.IdCount++;

            while (grafoAGM.Vertices.Count != grafo.Vertices.Count)
            {
                List <ArestaK> menorPesos = new List <ArestaK>();

                grafoAGM.Vertices.ForEach(v =>
                {
                    ArestaK aux = arestasK.Find(a => a.V1.Id == v.Id || a.V2.Id == v.Id);

                    if (!(aux is null))
                    {
                        menorPesos.Add(aux);
                    }
                });

                menorPesos.Sort((a1, a2) => a1.Peso - a2.Peso);

                ArestaK auxAresta = menorPesos[0];

                if (auxAresta.V1.Chefe.Id != auxAresta.V2.Chefe.Id)
                {
                    if (auxAresta.V2.Chefe != auxAresta.V2)
                    {
                        auxAresta.V1.Chefe = auxAresta.V2.Chefe;
                    }
                    else
                    {
                        auxAresta.V2.Chefe = auxAresta.V1.Chefe;
                    }

                    System.Console.WriteLine(auxAresta);

                    grafoAGM.InserirAresta(auxAresta.V1, auxAresta.V2, auxAresta.Peso);
                    grafoAGM.InserirAresta(auxAresta.V2, auxAresta.V1, auxAresta.Peso);

                    Aresta.IdCount++;
                }

                arestasK.Remove(auxAresta);
            }
        }
Exemple #11
0
 // -> Obtem todos os pesos de que ligam this em v
 public int[] GetPesos(Vertice v)
 {
     // -> Obtem todos os pesos de um vértice adjacente específico
     return(this.ListaAdjacencia.Where(a => a.Vertice.Id == v.Id).Select(a => a.Peso).ToArray());
 }
Exemple #12
0
 // -> busca na lista de adjacência de um vértice se ha incidência de v
 public bool IsAdjacente(Vertice v)
 {
     // -> Percorre toda a lista de adjacência e retorna se encontrar v
     return(this.ListaAdjacencia.Any(a => a.Vertice.Id == v.Id));
 }
Exemple #13
0
 // -> Remove um vértice adjacente e todas suas arestas
 public void RemoverAdjacente(Vertice v)
 {
     // -> Remove todas as incidências de v na lista de adjacência
     this.ListaAdjacencia.RemoveAll(a => a.Vertice.Id == v.Id);
 }
Exemple #14
0
 // -> Adiciona um vértice a lista de adjacência, junto ao peso
 public void AdicionarAdjacente(Vertice vertice, int peso)
 {
     // -> Adiciona uma nova aresta na lista de adjacência
     this.ListaAdjacencia.Add(new Aresta(vertice, peso));
 }
Exemple #15
0
 public Aresta(Vertice vertice, int peso)
 {
     this.Id      = IdCount;
     this.Vertice = vertice;
     this.Peso    = peso;
 }
Exemple #16
0
        public void Busca(int vertice, string[] cidade)
        {
            int indexCidade = 0, cidadePesquisa = 0;

            Console.Clear();
            Console.WriteLine("\n Cidades e seus respectivos vértices :");

            for (int i = 1; i <= vertice; i++)
            {
                Console.WriteLine("\n {0} = Vértice {1}", cidade[i - 1], i);
            }

            try
            {
                Console.Write("\n\n\n Digite o vértice da cidade de início :");
                indexCidade = int.Parse(Console.ReadLine());
            }
            catch (System.FormatException)
            {
                Console.WriteLine("\n\n Formato Inválido!!");
                Console.ReadLine();
                return;
            }

            try
            {
                Console.Write("\n\n\n Digite o vértice da cidade a ser pesquisada :");
                cidadePesquisa = int.Parse(Console.ReadLine());
            }
            catch (System.FormatException)
            {
                Console.WriteLine("\n\n Formato Inválido!!");
                Console.ReadLine();
                return;
            }

            Queue aux = new Queue();

            Vertice[] z = new Vertice[vertice];
            Vertice   numero;
            Queue     fila = new Queue();

            for (int i = 0; i < vertice; i++)
            {
                numero        = new Vertice();
                numero.numero = i;
                z[i]          = numero;
            }
            try
            {
                Vertice raiz = z[indexCidade - 1];
                raiz.visitado = true;
                fila.Enqueue(raiz.numero);
                int b = cidadePesquisa - 1;

                int cont = 0;
                while (fila.Count > 0)
                {
                    if (cont == 1)
                    {
                        break;
                    }
                    for (int j = 0; j < vertice; j++)
                    {
                        int i = Convert.ToInt32(fila.Peek());
                        if (matriz[i, j] == 1)
                        {
                            if (z[j].numero == b)
                            {
                                fila.Enqueue(z[j].numero);
                                Console.Clear();
                                Console.WriteLine("Foi encontrado o vertíce pesquisado");
                                Console.WriteLine("\n Pressione enter para ver as cidades que a busca passou para encontrar {0}", cidade[cidadePesquisa - 1]);
                                Console.ReadKey();

                                cont++;
                                break;
                            }
                            if (z[j].visitado == false)
                            {
                                z[j].visitado = true;
                                fila.Enqueue(z[j].numero);
                            }
                        }
                    }

                    aux.Enqueue(fila.Dequeue());
                }

                while (fila.Count > 0)
                {
                    aux.Enqueue(fila.Dequeue());
                }
                string[] texto = new string[vertice];
                Console.Clear();

                if (cont > 0)
                {
                    foreach (int c in aux)
                    {
                        if (c == b)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                        }

                        Console.WriteLine(cidade[c]);

                        texto[cont] = cidade[c];

                        Console.ForegroundColor = ConsoleColor.White;
                        cont++;
                    }
                }

                else
                {
                    Console.WriteLine("Não foi encontrado o vértice pesquisado,verifique se é um grafo conexo");
                }
                string path = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory), "out.xt");
                System.IO.File.WriteAllLines(path, texto);
                Console.ReadLine();
            }
            catch (System.IndexOutOfRangeException)
            {
                Console.WriteLine("\n\n Vértices Inválidos!!");
                Console.ReadKey();
            }
        }