简体   繁体   中英

Time and space complexity of recursion DFS when finding path in a maze

The question is : a man is looking for a target(which is marked as 9) in a 2D array, where 0 represents walls and 1 represents roads. The method should find if the man can find the target or not.

I came up with the solution using DFS easily, but got stuck when trying to find out the time and space complexity of my code.

public boolean find(int[][] grid) {
    if(grid == null || grid.length == 0 || grid[0].length == 0 || grid[0][0] == 0) return 0;
    return helper(grid,0,0);    
}

private boolean helper(int[][] grid,int x, int y) {
    if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length) {
        if(grid[x][y] == 0) return false;
        else if(grid[x][y] == 9) return true;
        else if(grid[x][y] == 1) {
            grid[x][y]=2;
            return helper(grid,x,y-1) || helper(grid,x+1,y) || helper(grid,x,y+1) || helper(grid,x-1,y);
        }
        else return false;
    }
    else return false;
}

I think the time and space complexity is O(mn), but I am not sure.

Generally speaking, DFS has a time complexity of O(m + n) and a space complexity of O(n), where n is the number of locations you can be in and m is the total number of connections between locations (if you're familiar with graph theory, n is the number of nodes and m is the number of edges). In your case, if you have a grid whose size is w × h, then n = wh (there's one place you can be for each grid location) and m ≤ 4wh (since each location is adjacent to at most four other locations). This means that the runtime will be O(wh) and the space complexity will be O(wh) as well.

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