0

I am using adjacency matrix to represent all the vertex of my weighted unidirectional large graph. In this graph no edge connects a vertex to itself. This makes all the diagonal elements of my adjacency matrix null. As my graph is large so in adjacency matrix i need not to save any elements in left triangle. Below is a small sample graph with adjacency matrix. This is the sample small graph with adjacency matrix

In an unidirectional graph left triangle is just mirror image of right triangle. i.e. adjacency_matrix[i][j], adjacency_matrix[j][i] are same. so why to store the left triangle. for a large graph this trick can save so much memory. At the same time diagonal elements are also zero since no edge connects a vertex to itself. i.e. adjacency_matrix[i][i] are zero. But how can i implement this? can 2D array be used here?

ravi
  • 6,140
  • 18
  • 77
  • 154

2 Answers2

3

Java doesn't really have 2D arrays, although there is syntatic sugar for allocating an array of arrays.

You probably just want:

int[][] weight = new int[N][];
for (int i = 0; i < N; i++) weight[i] = new int[N-1-i];

That will allocate the triangle you want. Then just index row r, col c at weight[r][c-r-1].

The other option is just to use a single array with

int[] weight = new int[N*(N-1)/2];

The indexing can be a bit more complicated to compute, but less allocation and pointer overhead.

Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • Yeah.... that what i want. i have to now think over index calculation in of 1D array. Thank you. – ravi Apr 07 '12 at 07:53
  • `int[][] weight = new int[N][]; for (int i = 0; i < N; i++) weight[i] = new int[N-1-i];` is cool. – ravi Apr 07 '12 at 09:08
  • After some brainstorming finally i can work with 1D `array` of dimension `n(n-1)/2` and any element can be accessed by the following formula- `index=n*row+col-(row+1)(row+2)/2` Here `index` is the index of 1D array and `row` and `col` belongs to 2D array having dimension `n*n` – ravi Apr 07 '12 at 10:22
1

You can use a jagged array.

int[][] matrix = new int[N][];
for (int i = 1; i <= N; i++) {
   matrix[i] = new int[N - i + 1];
   for (int j = 1; j <= N - i + 1; j++)
       matrix[i][j] = edgeValue;
}

Basically you allocate for each row as much as you need.

P.S Maybe I messed up some boundaries here, but you should still get the main point:)

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • I have a question here. If i designed an `array[m][n]`. and i assigned values to only some of it's elements. then what about the remaining elements which exists in this array? will they take any space in memory? – ravi Apr 07 '12 at 07:58
  • 1
    The point here is that you allocate for each row exactly as much as you need. For the first row for example 5, for the second row 4, and for the last row 1 element. It is not a plain two-dimensional array. It is called a zig-zag or jagged array. – Petar Minchev Apr 07 '12 at 08:01