简体   繁体   English

邻接矩阵中BFS的顺序是什么?

[英]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递归地,DFS 顺序将是

//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迭代地,DFS 顺序将是

//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. BFS 从某个节点开始,然后遍历它的所有邻居。

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.当遍历行时,它会将更多节点放入 BFS 的队列中,因为我们正在遍历行的列,队列中的第一个节点将是第一列中的第一个节点。

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.所以总的来说,我们可以说我们从某个节点 N 开始,然后遍历所有其他节点 n_1,..., n_n 然后转到 n_1 并遍历它所在行中的所有其他节点并将它们添加到队列中。 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]总共 M 个节点,假设我们从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...等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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