# 深度优先搜索DFS

### 二叉树的先序遍历：LeetCode144

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
//根、左、右
while(!stack.isEmpty() || root != null) {
if(root != null) {
stack.offer(root);
root = root.left;
} else {
root = stack.pollLast();
root = root.right;
}
}
return res;
}
}


### 二叉树的中序遍历：LeetCode94

class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
//左、根、右
while(!stack.isEmpty() || root != null) {
if(root != null) {
stack.offer(root);
root = root.left;
} else {
root = stack.pollLast();
root = root.right;
}
}
return res;
}
}


### 二叉树的后序遍历：LeetCode145

class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
//根、右、左的倒序
while(!stack.isEmpty() || root != null) {
if(root != null) {
res.offerFirst(root.val);
stack.offer(root);
root = root.right;
} else {
root = stack.pollLast();
root = root.left;
}
}
return res;
}
}


### 不同路径III：LeetCode980

在二维网格 grid 上，有 4 种类型的方格：

1 表示起始方格。且只有一个起始方格。
2 表示结束方格，且只有一个结束方格。
0 表示我们可以走过的空方格。
-1 表示我们无法跨越的障碍。


class Solution {
boolean[][] isUsed;
int count;
public int uniquePathsIII(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
isUsed = new boolean[m][n];
int startm = 0, startn = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == 0)
isUsed[i][j] = false;
else if(grid[i][j] == -1)
isUsed[i][j] = true;
else if(grid[i][j] == 1) {
startm = i;
startn = j;
isUsed[i][j] = false;
} else
isUsed[i][j] = true;
}
}
count = 0;
dfs(grid, startm, startn);
return count;
}
private void dfs(int[][] grid, int curm, int curn) {
isUsed[curm][curn] = true;
if(curm > 0) {
if(grid[curm - 1][curn] == 2) {
if(allUsed())
count++;
} else if(!isUsed[curm - 1][curn])
dfs(grid, curm - 1, curn);
}
if(curn > 0) {
if(grid[curm][curn - 1] == 2) {
if(allUsed())
count++;
} else if(!isUsed[curm][curn - 1])
dfs(grid, curm, curn - 1);
}
if(curm < grid.length - 1) {
if(grid[curm + 1][curn] == 2) {
if(allUsed())
count++;
} else if(!isUsed[curm + 1][curn])
dfs(grid, curm + 1, curn);
}
if(curn < grid[0].length - 1) {
if(grid[curm][curn + 1] == 2) {
if(allUsed())
count++;
} else if(!isUsed[curm][curn + 1])
dfs(grid, curm, curn + 1);
}
isUsed[curm][curn] = false;
}
private boolean allUsed() {
for(int i = 0; i < isUsed.length; i++) {
for(int j = 0; j < isUsed[0].length; j++) {
if(!isUsed[i][j])
return false;
}
}
return true;
}
}


©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试