DFS template
void dfs()//参数用来表示状态 {
if(到达终点状态){
return;
}
if(越界或者是不合法状态)
return;
if(特殊状态)//剪枝
return ;
for(扩展方式){
if(扩展方式所达到状态合法){
//根据题意来添加
修改操作;
标记;
dfs();
//是否还原标记根据题意,如果加上(还原标记)就是 回溯法
(还原标记);
}
}
}
Solution for Leetcode 797
Note that add(new ArrayList(path)) so that have a copy or otherwise it shares the same copy
class Solution {
List<List<Integer>> ans = new ArrayList();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
dfs(0, new ArrayList(), graph);
return ans;
}
public void dfs(int curNode, List<Integer> path, int[][] graph){
path.add(curNode);
if(curNode == graph.length - 1){
ans.add(new ArrayList(path));
return;
}
for(int nextNode : graph[curNode]){
dfs(nextNode, path, graph);
path.remove(path.size() - 1);
}
}
}
Solution for leetcode 130 (DFS in a matrix)
Idea: find every 'O' that is on the edge and do a dfs to change it to *
then iterate through the board again to change 'O' to 'X' and change '*' to 'O'
class Solution {
public void solve(char[][] board) {
boolean visited[][] = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if((i == 0 || i == board.length - 1 || j == 0 || j == board[0].length - 1) && board[i][j] == 'O' ){
dfs(i, j, board,visited);
}
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}
if(board[i][j] == '-'){
board[i][j] = 'O';
}
}
}
}
public void dfs(int i, int j, char[][]board, boolean[][]visited){
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] == true){
return;
}
if(board[i][j] == 'O'){
visited[i][j] = true;
board[i][j] = '-';
dfs(i - 1, j, board, visited);
dfs(i + 1, j, board, visited);
dfs(i, j + 1, board, visited);
dfs(i, j - 1, board, visited);
}
}
}
Solution for leetcode 802
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int[] color = new int[graph.length];
List<Integer> ans = new ArrayList();
for (int i = 0; i < graph.length; ++i)
if (dfs(i, graph, color))
ans.add(i);
return ans;
}
//0 unvisited, 1 safe, 2 unsafe
public boolean dfs(int index, int[][] graph, int[]color){
if(color[index] != 0){
return color[index] == 1;
}
color[index] = 2;
for (int cur: graph[index]) {
if(color[cur] == 2 || !dfs(cur, graph, color)){
return false;
}
}
color[index] = 1;
return true;
}
}
Solution for leetcode 133
class Solution {
HashMap <Node, Node> visited = new HashMap <> ();
public Node cloneGraph(Node node) {
if (node == null) {
return node;
}
if (visited.containsKey(node)) {
return visited.get(node);
}
Node cloneNode = new Node(node.val, new ArrayList());
visited.put(node, cloneNode);
for (Node neighbor: node.neighbors) {
cloneNode.neighbors.add(cloneGraph(neighbor));
}
return cloneNode;
}
}