简体   繁体   中英

An array of mutable arrays in Swift

I am trying to implement an adjacency list in Swift, basically a collection of lists, or I guess a collection of mutable arrays. I wrote a Depth Search First implementation in Java for and I would like to write the same in Swift. This code of for the Graph representation. Any ideas of how to do this? Here is the code in Java if that helps:

public class Graph
{

    private List<Integer>[] adj;

    public Graph(int numberOfVertices)
    {
         adj = (List<Integer>[]) new List[numberOfVertices];
         ...
         for(int i = 0; i < numberOfVertices; i++)
               adj[i] = new ArrayList<Integer>(); 

    }

Even knowing how to declare a variable that contains an array of mutable arrays would be great. I didn't find any information on how to do this in the book released by apple or the web.

You can declare an array of arrays simply by doing the following:

var nestedArrays : [[Int]] = []
nestedArrays.append([1, 2])
nestedArrays[0].append(3)
nestedArrays // [[1, 2, 3]]

If you wanted to have it start with a number of empty arrays you could do the following:

var nestedArrays = [[Int]](count: 10, repeatedValue: [])

Then it would start with 10 empty arrays

Your class could look like this:

class Graph {
    var adj : [[Int]]

    init(numberOfVertices: Int) {
        adj = [[Int]](count: numberOfVertices, repeatedValue: [])
    }
}

Or if you would like to create a class that can have a graph of any type of object you can use generics:

class Graph<T> {
    var adj : [[T]]

    init(numberOfVertices: Int) {
        adj = [[T]](count: numberOfVertices, repeatedValue: [])
    }
}

This is the Swift equivalent to your code:

class Graph {
    var adj : Array<Array<Int>>

    init (_ numberOfVertices: Int) {
        adj = Array<Array<Int>> (count: numberOfVertices, repeatedValue: [])
        for i in 1..numberOfVertices {
            adj[i] = Array<Int> ()
        }
    }
}

and some 'tests':

 11> var gr = Graph(5)
gr: Graph = {
  adj = size=5 {
    [0] = size=0
    [1] = size=0
    [2] = size=0
    [3] = size=0
    [4] = size=0
  }
}
 12> gr.adj[1].append (2)
 13> gr.adj[1].append (10)
 ...
 15> gr.adj[4].append (7)
 16> gr.adj
$R5: Int[][] = size=5 {
  [0] = size=0
  [1] = size=2 {
    [0] = 2
    [1] = 10
  }
  [2] = size=0
  [3] = size=0
  [4] = size=1 {
    [0] = 7
  }
}
 17> gr.adj[4][0]
$R7: Int = 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM