[英]Trying to understand why the Space Complexity of searching through a grid using BFS is O(m * n), where m is no. of rows and n is no. of cols
我試圖了解在網格中使用 BFS 的空間復雜性。 當我們從 m * n 維網格中的一個單元格開始時,我們可以向上、向右、向下和向左 go。
我的理解是,如果我們從中間的某個地方開始,空間復雜度應該是 O(m + n)。 如果我們從 4 個角之一開始,它應該是 O(min(m, n))。 所以總的來說,考慮到我們不知道從哪里開始,在最壞的情況下它可能是 O(m + n)。
我嘗試通過在網格中單獨啟動所有單元格並計算隊列的最大大小並了解空間復雜度來在本地進行測試。
我的測試代碼:
class Solution {
int max = 0;
public static void main(String[] args) {
Solution solution = new Solution();
int rows = 200, cols = 200;
int[][] grid = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
solution.initializeGrid(grid, rows, cols);
solution.processGrid(grid, rows, cols, i, j);
}
}
System.out.println("Highest queue size is " + solution.max);
}
private void initializeGrid(int[][] grid, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
grid[i][j] = 1;
}
}
}
private void processGrid(int[][] grid, int rows, int cols, int row, int col) {
Queue<int[]> queue = new LinkedList<>();
int[] childrenRows = new int[]{-1, 0, 1, 0};
int[] childrenCols = new int[]{0, 1, 0, -1};
queue.add(new int[]{row, col});
grid[row][col] = 0;
while (!queue.isEmpty()) {
max = Math.max(max, queue.size());
int[] parent = queue.poll();
int pr = parent[0], pc = parent[1];
for (int i = 0; i < 4; i++) {
int cr = pr + childrenRows[i], cc = pc + childrenCols[i];
if (cr >= 0 && cr < rows && cc >= 0 && cc < cols && grid[cr][cc] == 1) {
queue.add(new int[]{cr, cc});
grid[cr][cc] = 0;
}
}
}
}
}
給定輸入 m = 200, n = 200 的 output 是
The highest queue size is 399. This value proportional to O(m + n)
我知道這不是計算空間復雜度的正確方法,但我想知道隊列使用的確切空間以及它是否與 O(m * n) 成正比。
我嘗試了其他更大的輸入。 盡管如此,空間復雜度仍然是 O(m + n)。
我在這里錯過了什么嗎? 有人可以幫我理解邏輯嗎?
您正在關注最大隊列大小,但您在算法開始時就達到了O(m * n)
空間:
boolean[][] visited = new boolean[rows][cols]
您剛剛分配了O(m * n)
空間!
在通用 BFS 中,您必須跟蹤所有訪問過的狀態,因此空間限制不能低於狀態總數。
也就是說O(m * n)
僅在網格可能很復雜時才有效。 如果它只是一個大小為 mxn 的完整網格,您可以優化算法以使其成為O(m + n)
空間——您不需要在 memory 中保留訪問單元格的整個歷史記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.