How do I add a matrix to an edge of the graph?

Asked

Viewed 859 times

2

My graph is implemented as an adjacency matrix. The graph is acyclic. I intend to create a method that takes two nodes and creates an edge from one to the other with an Nxm matrix. What’s missing or what’s wrong?

public class Graph {

    /** Atributos da classe Graph */

    int [][] grafoo; // o grafo está representada por uma matriz de adjacência


    /** Construtor da classe Graph */ 

    public Graph (int dim)
    {
        grafoo = new int [dim][dim];

        int i=0, j;     
        while(i<dim)
        {
            j=0;
            while(j<dim)
            {
                grafoo[i][j]=0;
                j++;
            }
            i++;
        }
    }

    /** Definição do Método */

    void add_edge(int i, int j) //recebe dois nós e adiciona ao grafo uma aresta de um nó para outro com uma matriz de NxM.

        int[][] E = new int[N][M];      
        grafoo[i][j]= E;        
    }
  • This question is very broad, need to define which problem is occurring.

  • The problem is I don’t know how to add a matrix to an edge. The graph is constructed so as to be represented by an adjacency matrix (see constructor method), and then my goal is to create a function (add_edge) that takes 2 us and adds an edge matrix.

  • Know if q always q the graph is represented by an adjacency matrix and qnd there is an edge between 2 nos, the respective input and 1. In my case, I wanted q instead of representing an edge by 1, to put in that input an Nxm matrix (example 4x5).

1 answer

1


The problem with your attribute grafoo, it is a matrix of int primitive, when to receive another matrix, need to be more complex.

There are two approaches:

The first is to use the Object type in grafoo, that facilitates much in the access to this second matrix, since it is enough to access an edge of the grafoo, which returns an array, and then access the array again. The Code would look like this:

public class Graph {

    /** Atributos da classe Graph */

    Object [][] grafoo; // o grafo está representada por uma matriz de adjacência

    /** Construtor da classe Graph */ 

    public Graph (int dim)
    {
        grafoo = new Object [dim][dim];
        // Nesse caso não precisamos inicializar o grafoo, porque ele ja esta com todos os valores null, se fosse int também não precisaria,
        // já que por ser diferentemente do C, a JVM atribui valor zero para as áreas de memória após a alocação.
    }

    /** Definição do Método */
    public void add_edge(int i, int j) //recebe dois nós e adiciona ao grafo uma aresta de um nó para outro com uma matriz de NxM.
    {
        int[][] E = new int[N][M];      
        grafoo[i][j] = E; // Agora isso é totalmente válido, no caso anterior gerava erro de compilação.        
    }

    public int[][] get_edge(int i, int j)
    {
        return (int[][]) grafoo[i][j]; // Retorna a matriz relativa à aresta i,j
    }

    public void update_edge(int i, int j, int[][] new_edge) // Atualização por sobreescrita
    {
        grafoo[i][j] = new_edge;
    }

    public void update_edge(int i, int j, int k, int l, int value) // Atualização de célula
    {
        int[][] matrix = (int[][]) grafoo[i][j];
        matrix[k][l] = value;
    }
}

This approach is much simpler, but has the annoyance that, with complexity increasing, if you change what you keep inside the edges of the grafoo, you will have to review all the sites that access the grafoo so that no error occurs. Specifically in cast which is done in the get_edge.

The second alternative is to use int[][] instead of Object, leaving the statement of grafoo thus: int [][][][], which I find very strange and more confusing to access, however any "mistake" will result in compilation error and not in runtime as in the first alternative.

  • Thank you very much for the correction! Yes, the problem was in the graph definition.

  • I have another question here. And if you want to make another method, let’s imagine that it is called update_egde, where it receives two nodes and modifies this matrix q is between these two nodes, that is, updating this matrix with new entries. How would it look? From my point of view, the code is not equal to add_edge?

  • It would be like get_edge, but what would the update type look like? Would it be a new matrix or update a certain matrix cell? I updated the example with two update types that I thought at the time. If you have another form that is in mind just let me know.

  • it would be more to update the whole matrix because all the parameters contained in it will change. Two questions that came up: 1st int[][] E = new int[N][M]; Do I have to replace M and N by numbers? Otherwise it is making a mistake on this line. 2 what is the meaning of (int[][]) in this line int[][] matrix = (int[][]) grafoo[i][j];

  • On the first question: vc defined M and N where? They do not need to be fixed numbers, but you need to define M and N before using. About the second, it’s called a cast. Take a look at this link ( http://www.javabeginner.com/learn-java/java-object-typecasting) to better understand how casting works in Java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.