Convert Adjacency Matrix to Adjacency List - aloalgo

Convert Adjacency Matrix to Adjacency List

Medium

An adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not. For an unweighted graph, a value of 1 (or true) at matrix[i][j] indicates an edge from vertex i to vertex j, and 0 (or false) indicates no edge. For a directed graph, an edge from i to j does not necessarily imply an edge from j to i.An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex. For a graph with N vertices, an adjacency list typically consists of N lists, where the i-th list contains all vertices j such that there is an edge from i to j.Your task is to convert a given adjacency matrix into its corresponding adjacency list representation. The input adjacency matrix adjMatrix will be a square matrix where adjMatrix[i][j] = 1 if there is an edge from vertex i to vertex j, and 0 otherwise. The output should be an array of arrays (or list of lists), where the i-th inner array contains the indices of all vertices adjacent to vertex i.

Example 1

Input
[
  [0, 1, 0],
  [0, 0, 1],
  [1, 0, 0]
]
Output
[
  [1],
  [2],
  [0]
]
Explanation:

From vertex 0, there is an edge to vertex 1. From vertex 1, there is an edge to vertex 2. From vertex 2, there is an edge to vertex 0.

Example 2

Input
[
  [0, 1, 1],
  [1, 0, 0],
  [1, 0, 0]
]
Output
[
  [1, 2],
  [0],
  [0]
]
Explanation:

From vertex 0, there are edges to vertices 1 and 2. From vertex 1, there is an edge to vertex 0. From vertex 2, there is an edge to vertex 0.

Example 3

Input
[
  [0, 1, 0],
  [0, 0, 0],
  [0, 0, 0]
]
Output
[
  [1],
  [],
  []
]
Explanation:

From vertex 0, there is an edge to vertex 1. Vertices 1 and 2 have no outgoing edges.

Loading...
Input
[
  [0, 1, 0],
  [0, 0, 1],
  [1, 0, 0]
]
Output
[
  [1],
  [2],
  [0]
]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!