# DFS

| <p><br>The Time complexity of BFS is O(V + E) when Adjacency List is used and O(V^2) when Adjacency Matrix is used, where V stands for vertices and E stands for edges.</p> |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

The idea:

Base on the current situation to recursive decide further status, and so on. until all the unrevealed status is decided.

So, for most of the cases, we must have a firmed status, and we base on that status to derive all the other unknown status. and so on, until we have all the answers.&#x20;

```java
 public void mainQuestion(char[][] grid) {
        int m = grid.length;
        if(m == 0) return 0;
        int n = grid[0].length;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(/*grid[i][j] is firmed status*/){
                    dfs(grid, i, j);
                }
            }
        }
    }
    public void dfs(char[][] grid, int i, int j){
        //some region/leagality check
        if(i < 0 || j < 0 || i >= grid.length
           || j >= grid[0].length || grid[i][j] == '0') return;
        
        //set that to visied(ie. decided)
        grid[i][j] = '0';
        
        //derive to unknown status
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
        
    }
```

&#x20;

```java
        int[][] dirs = new int[][]{{0,1}, {1,0}, {0,-1}, {-1,0}};

```

**DFS思路**

* 推演的過程中要告訴我們什麼?&#x20;
  * 狀態的更新 (global variable)&#x20;
    * **lca**
    * deepest
  * 推演的過程需要什麼 (input of dfs)
  * 子問題的答案 (return value)
    * node 的子孫裡最底層的leaf 深度
  * 結算 (要在推演前or後面?)
