Correção de código java.

Algoritmos
Tenho um código em JAVA, porém ele não está saindo com o resultado desejado pelo enunciado do trabalho. Queria que você me ajudasse a corrigi-lo. O código tem que pegar os caminhos da arvore, fazer a soma das pontuações da raiz até as folhas (fim dos caminhos) e escolher o caminho com maior pontuação. import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class FrutinhasSaborosas2 { static class Node { int value; List children; Node(int value) { this.value = value; this.children = new ArrayList<>(); } } public static void main(String[] args) { String fileName = "casoe30.txt"; // Coloque o caminho correto do arquivo aqui List lines = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { lines.add(line); System.out.println(line); } } catch (FileNotFoundException e) { throw new RuntimeException("Arquivo não encontrado: " + fileName, e); } catch (IOException e) { e.printStackTrace(); } // Conversão das linhas para matriz char[][] treeMatrix = convertLinesToMatrix(lines); Node root = processTree(treeMatrix); // Impressão da estrutura da árvore System.out.println("Estrutura da árvore:"); printTree(root, 0); // Encontrar o maior caminho e sua soma List maxPath = new ArrayList<>(); int maxSum = caminhoMaximo(root, maxPath); // Imprime o maior caminho e sua soma System.out.println("\nMaior Caminho: " + maxPath); System.out.println("Soma máxima: " + maxSum); } // Converte as linhas do arquivo para uma matriz de caracteres private static char[][] convertLinesToMatrix(List lines) { int numRows = lines.size(); int numCols = lines.stream().mapToInt(String::length).max().orElse(0); char[][] treeMatrix = new char[numRows][numCols]; for (int i = 0; i < numRows; i++) { String line = lines.get(i); for (int j = 0; j < line.length(); j++) { treeMatrix[i][j] = line.charAt(j); } } return treeMatrix; } // Processa a matriz para construir a árvore de baixo para cima private static Node processTree(char[][] treeMatrix) { int numRows = treeMatrix.length; int numCols = treeMatrix[0].length; Node[][] nodes = new Node[numRows][numCols]; // Inicializa a matriz de nós for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { char current = treeMatrix[i][j]; if (Character.isDigit(current)) { nodes[i][j] = new Node(Character.getNumericValue(current)); } else if (current == '#') { nodes[i][j] = new Node(0); // Folhas marcadas como # têm valor 0 } } } // Conecta os nós, construindo a árvore de baixo para cima for (int i = numRows - 2; i >= 0; i--) { // Começa do penúltimo nível para cima for (int j = 0; j < numCols; j++) { if (nodes[i][j] != null) { Node parentNode = nodes[i][j]; // Checa os filhos possíveis para cada tipo de galho if (treeMatrix[i][j] == '|') { if (i + 1 < numRows && nodes[i + 1][j] != null) { parentNode.children.add(nodes[i + 1][j]); } } else if (treeMatrix[i][j] == '/') { if (i + 1 < numRows && j + 1 < numCols && nodes[i + 1][j + 1] != null) { parentNode.children.add(nodes[i + 1][j + 1]); } } else if (treeMatrix[i][j] == '\\') { if (i + 1 < numRows && j - 1 >= 0 && nodes[i + 1][j - 1] != null) { parentNode.children.add(nodes[i + 1][j - 1]); } } else if (treeMatrix[i][j] == 'V' || treeMatrix[i][j] == 'W') { if (i + 1 < numRows && j - 1 >= 0 && nodes[i + 1][j - 1] != null) { parentNode.children.add(nodes[i + 1][j - 1]); } if (i + 1 < numRows && nodes[i + 1][j] != null) { parentNode.children.add(nodes[i + 1][j]); } if (i + 1 < numRows && j + 1 < numCols && nodes[i + 1][j + 1] != null) { parentNode.children.add(nodes[i + 1][j + 1]); } } } } } // A raiz é o nó da primeira linha (última linha no contexto da construção) Node root = null; for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { if (nodes[i][j] != null) { root = nodes[i][j]; break; } } if (root != null) break; } System.out.println("CACETA: " + (root != null ? root.value : "Nenhuma raiz encontrada")); return root; } // Encontra o caminho com a soma máxima a partir da raiz public static int caminhoMaximo(Node root, List path) { List maxPath = new ArrayList<>(); int maxSum = caminhoMaximoAux(root, maxPath); path.addAll(maxPath); return maxSum; } private static int caminhoMaximoAux(Node node, List path) { if (node == null) return 0; // Caso base: nó folha if (node.children.isEmpty()) { path.add(node.value); return node.value; } // Encontrar o caminho com a maior soma entre todos os filhos List maxChildPath = new ArrayList<>(); int maxSum = Integer.MIN_VALUE; for (Node child : node.children) { List currentChildPath = new ArrayList<>(); int childSum = caminhoMaximoAux(child, currentChildPath); if (childSum > maxSum) { maxSum = childSum; maxChildPath = currentChildPath; } } path.add(node.value); path.addAll(maxChildPath); return node.value + maxSum; } // Imprime a estrutura da árvore private static void printTree(Node node, int depth) { if (node == null) return; System.out.println(" ".repeat(depth * 2) + "Nó com valor: " + node.value); // Percorre todos os filhos for (Node child : node.children) { printTree(child, depth + 1); } } }
Foto de Ioannis C.
Ioannis perguntou há 6 dias
1 resposta
Minerva
Inteligência Artificial do Profes
Respondeu há 6 dias

Pelo que você descreveu, parece que há alguns problemas a serem resolvidos para garantir que o código funcione corretamente. Vou fazer algumas correções e melhorias no seu código:

  1. Identificação correta da raiz: A raiz deve ser o primeiro nó da matriz que não possui pai.
  2. Correção na construção da árvore de baixo para cima: Corrigir as condições de adição dos filhos para os nós.
  3. Identificação do maior caminho e soma: Certificar de que a lógica para encontrar o maior caminho funcione corretamente.

Aqui está o código corrigido com algumas melhorias:

```java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*;

public class FrutinhasSaborosas2 { static class Node { int value; List children;

    Node(int value) {
        this.value = value;
        this.children = new ArrayList<>();
    }
}

public static void main(String[] args) {
    String fileName = "casoe30.txt"; // Coloque o caminho correto do arquivo aqui
    List<String> lines = new ArrayList<>();

    try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = br.readLine()) != null) {
            lines.add(line);
            System.out.println(line);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Arquivo não encontrado: " + fileName, e);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Conversão das linhas para matriz char[][] treeMatrix = convertLinesToMatrix(lines);
    Node root = processTree(treeMatrix);

    // Impressão da estrutura da árvore
    System.out.println("Estrutura da árvore:");
    printTree(root, 0);

    // Encontrar o maior caminho e sua soma
    List<Integer> maxPath = new ArrayList<>();
    int maxSum = caminhoMaximo(root, maxPath);

    // Imprime o maior caminho e sua soma
    System.out.println("\nMaior Caminho: " + maxPath);
    System.out.println("Soma máxima: " + maxSum);
}

// Converte as linhas do arquivo para uma matriz de caracteres
private static char[][] convertLinesToMatrix(List<String> lines) {
    int numRows = lines.size();
    int numCols = lines.stream().mapToInt(String::length).max().orElse(0);
    char[][] treeMatrix = new char[numRows][numCols];

    for (int i = 0; i < numRows; i++) {
        String line = lines.get(i);
        for (int j = 0; j < line.length(); j++) {
            treeMatrix[i][j] = line.charAt(j);
        }
    }
    return treeMatrix;
}

// Processa a matriz para construir a árvore de baixo para cima
private static Node processTree(char[][] treeMatrix) {
    int numRows = treeMatrix.length;
    int numCols = treeMatrix[0].length;
    Node[][] nodes = new Node[numRows][numCols];

    // Inicializa a matriz de nós
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            char current = treeMatrix[i][j];
            if (Character.isDigit(current)) {
                nodes[i][j] = new Node(Character.getNumericValue(current));
            } else if (current == '#') {
                nodes[i][j] = new Node(0); // Folhas marcadas como # têm valor 0
            } else {
                nodes[i][j] = null; // ramos ou espaços vazios serão ignorados
            }
        }
    }

    // Conecta os nós, construindo a árvore de baixo para cima
    for (int i = numRows - 2; i >= 0; i--) { // Começa do penúltimo nível para cima
        for (int j = 0; j < numCols; j++) {
            if (nodes[i][j] != null) {
                Node parentNode = nodes[i][j];
                // Checa os filhos possíveis para cada tipo de galho
                if (treeMatrix[i][j] == '|') {
                    if (i + 1 < numRows && nodes[i + 1][j] != null) {
                        parentNode.children.add(nodes[i + 1][j]);
                    }
                } else if (treeMatrix[i][j] == '/') {
                    if (i + 1 < numRows && j - 1 >= 0 && nodes[i + 1][j - 1] != null) {
                        parentNode.children.add(nodes[i + 1][j - 1]);
                    }
                } else if (treeMatrix[i][j] == '\\') {
                    if (i + 1 < numRows && j + 1 < numCols && nodes[i + 1][j + 1] != null) {
                        parentNode.children.add(nodes[i + 1][j + 1]);
                    }
                } else if (treeMatrix[i][j] == 'V' || treeMatrix[i][j] == 'W') {
                    if (i + 1 < numRows && j - 1 >= 0 && nodes[i + 1][j - 1] != null) {
                        parentNode.children.add(nodes[i + 1][j - 1]);
                    }
                    if (i + 1 < numRows && nodes[i + 1][j] != null) {
                        parentNode.children.add(nodes[i + 1][j]);
                    }
                    if (i + 1 < numRows && j + 1 < numCols && nodes[i + 1][j + 1] != null) {
                        parentNode.children.add(nodes[i + 1][j + 1]);
                    }
                }
            }
        }
    }

    // A raiz é o nó da primeira linha (última linha no contexto da construção)
    Node root = null;
    for (int j = 0; j < numCols; j++) {
        if (nodes[0][j] != null) {
            root = nodes[0][j];
            break;
        }
    }

    if (root == null) {
        throw new RuntimeException("Raiz não encontrada.");
    }

    return root;
}

// Encontra o caminho com a soma máxima a partir da raiz
public static int caminhoMaximo(Node root, List<Integer> path) {
    if (root == null) return 0;

    caminhoMaximoAux(root, path);
    return path.stream().mapToInt(Integer::intValue).sum();
}

private static int caminhoMaximoAux(Node node, List<Integer> path) {
    if (node == null) return 0;

    // Caso base: nó folha
    if (node.children.isEmpty()) {
        path.add(node.value);
        return node.value;
    }

    // Encontrar o caminho com a maior soma entre todos os filhos
    List<Integer> maxChildPath = null;
    int maxSum = Integer.MIN_VALUE;

    for (Node child : node.children) {
        List<Integer> currentChildPath = new ArrayList<>();
        int childSum = caminhoMaximoAux(child, currentChildPath);

        if (childSum > maxSum) {
            maxSum = childSum;
            maxChildPath = currentChildPath;
        }
    }

    if (maxChildPath != null) {
        path.add(node.value);
        path.addAll(maxChildPath);
    }

    return node.value + maxSum;
}

// Imprime a estrutura da árvore
private static void printTree(Node node, int depth) {
    if (node == null) return;

    System.out.println(" ".repeat(depth * 2) + "Nó com valor: " + node.value);

    // Percorre todos os filhos
    for (Node child : node.children) {
        printTree(child, depth + 1);
    }
}

} ```

Modificações chave: 1. Construção da árvore: Clarifiquei a lógica para identificar e conectar os filhos aos pais. 2. Processo de identificação da raiz: Identifiquei a raiz corretamente a partir do primeiro nível. 3. Caminho máximo: Ajustei a função caminhoMaximoAux para assegurar que o caminho correto e sua soma sejam calculados e retornados.

Certifique-se de ajustar o código conforme necessário para o formato específico de entrada de dados no arquivo "casoe30.txt".

Envie uma dúvida e receba resposta imediata

Respostas da IA e de professores particulares
Enviar dúvida
Tenha sua atividade, tarefa, lista de exercícios, ou projeto resolvida por um professor especialista
Você define o prazo
Interação com o professor por chat
Se não gostar da resolução, reembolsamos
Enviar tarefa

Envie suas dúvidas pelo App