dfs笔记,为什么,网格的深度优先搜索java板
130. 被围绕得区域Tuesday, August 31, 20219:01 AMclass Solution { public void solve(char[][] board) { // 思路:从外围走。如果是o 把他改为* // 路径,上下左右搜索。其他也可可以。 // dfs // 重新遍历。输出结果。把o 改为x, 把* 改为o if (board == null || board.length == 0) return; int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // 从边缘o开始搜索 if( (i == 0 || j == 0|| i== m-1 || j == n-1) && board[i][j] == 'O'){ // board[i][j] = '*' // dfs(board[i][j]);//这样写。传入得是一个char , 所以不行,得加两个参入参数,i, j dfs(board, i, j); } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') { board[i][j] = 'X'; } if (board[i][j] == '*') { board[i][j] = 'O'; } } } } // private void dfs(char[][] board){ private void dfs(char[][] board, int i , int j){ //一定要写递归终止条件 if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] == 'X' || board[i][j] == '*') { // board[i][j] == '*' 说明已经搜索过了. return; } // (i = 0 || j = 0|| i= m-1 || j = n-1)边界位置 board[i][j] = '*'; // 深搜,定义路径 // dfs(board[i-1][j]); 这样写不行 // dfs(board[i+1][j]); // dfs(board[i][j-1]); // dfs(board[i][j+1]); dfs(board,i-1,j); dfs(board,i+1,j); dfs(board,i,j-1); dfs(board,i,j+1); }}