简体   繁体   中英

What is the order for BFS in adjacency matrix?

Given an adjacency matrix

int[][] grid = new int[5][5];

Recursively, the DFS order would be

//y = Row
//x = Column

//Down
grid[y + 1][x];

//Up
grid[y - 1][x];

//Right
grid[y][x + 1];

//Left
grid[y][x - 1];

Iteratively, the DFS order would be

//Left
stack.push(y);
stack.push(x - 1);

//Right
stack.push(y);
stack.push(x + 1);

//Up
stack.push(y - 1);
stack.push(x);

//Down
stack.push(y + 1);
stack.push(x);

BFS starts at some node and then goes over all it's neighbours.

If we have an adjacency matrix it means that it will start at some row and will go over all columns of this row.

When going over the row it will put more nodes inside BFS's queue and because we're going over the columns of the row the first node in the queue will be the first node in the first column.

So in total we can say the we start at some node N, then go over all other nodes n_1,..., n_n then go to n_1 and go over all other nodes in it's row and add them to the queue. Then we continue to some other row of a node we added to the queue earlier.

M nodes in total and let's say that we start with the node at grid[0][0]

grid[0][0], ..., grid[0][M-1]

//Added to the queue grid[0][1], grid[0][2]

grid[1,0], ..., grid[1][M-1]

//Added to the queue grid[1][3], grid[1][4]

grid[2,0], ..., grid[2][M-1]

and so on...

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