深度优先搜索(DFS)与广度优先搜索(BFS)、LetCode题目

目录

DFS

BFS

LetCode

DFS

代码结构

200. 岛屿数量

463. 岛屿的周长

BFS

代码结构

542. 01 矩阵

102. 二叉树的层序遍历



DFS

注标记是否访问过方法:1、直接修改输入的数据   2、利用额外的数据结构(矩阵或hash表)

Step4: 判断是否访问过 和 抵达目的地,访问过就不尝试,抵达目的地返回true

代码结构:

	DFS(输入数据:矩阵或链表或树,起始点){
		建栈
		存储访问过节点seen: Map 或 改变输入数据
		while( 栈不为空 ) {
			访问栈顶,pop()
			for(从栈顶出发访问,所有下一个节点(状态))
				if (如果没有访问 或 合法)
					加入栈,加入seen或改变输入数据
		}
	}

BFS

代码结构:

	BFS(输入数据:矩阵或链表或树,起始点){
		建队列
		存储访问过节点seen: Map 或 改变输入数据
		while( 队列不为空 ) {
			访问队头,poll()
			for(从队头出发访问,所有下一个节点(状态))
				if (如果没有访问 或 合法)
					加入队,访问:加入seen或改变输入数据
                                                                                if(到达终点)返回
		}
	}

 

LetCode

DFS

代码结构

	DFS(输入数据:矩阵或链表或树,起始点){
		建栈
		存储访问过节点seen: Map 或 改变输入数据
		while( 栈不为空 ) {
			访问栈顶,pop()
			for(从栈顶出发访问,所有下一个节点(状态))
				if (如果没有访问 或 合法)
					加入栈,加入seen或改变输入数据
		}
	}

200. 岛屿数量

	public int numIslands(char[][] grid) {
		int count = 0 ;
		int [] dx = new int[] {0,-1,0,1} ;
		int [] dy = new int[] {-1,0,1,0} ;
		
		for(int i = 0; i < grid.length; i++) {
			for(int j = 0; j < grid[0].length; j++) {
				if(grid[i][j] == '1') {
					DFS(grid, i, j, dx, dy) ;
					count ++ ;
				}
			}
		}
		return count ;
	}
	
	public static void DFS(char[][] grid, int x, int y, int[] dx, int[] dy) {
		Stack<Integer[]> stack = new Stack<Integer[]>() ;
		grid[x][y] = '0' ;
		stack.push(new Integer[] {x,y}) ;
		while(!stack.isEmpty()) {
			Integer [] temp = stack.pop() ;
			x = temp[0]; y = temp[1] ;
			for( int d = 0; d < 4; d++) {
				int i = x + dx[d] , j = y + dy[d] ; 
				if( i>=0 && i < grid.length && j>=0 && j < grid[0].length && grid[i][j] != '0') {
					grid[i][j] = '0';
					stack.push(new Integer[] {i,j}) ;
				}
			}
		}
	}

注意四个方向的走法。

463. 岛屿的周长

class Solution {
    public int islandPerimeter(int[][] grid) {
        int count = 0 ;
        int[] dx = {0,-1,0,1} ;
        int[] dy = {-1,0,1,0} ;
        for( int i = 0; i < grid.length; i ++){
            for( int j = 0; j < grid[0].length; j ++){
                if(grid[i][j] == 1){
                    count = DFS(grid, dx, dy, i, j) ;
                    return count ;
                }
            }
        }
        return count ;
    }
    public int DFS(int[][] grid, int[] dx, int[] dy, int x, int y){
        int count = 0 ;
        Stack<int []> stack = new Stack<>() ;
        grid[x][y] = 2;
        stack.push(new int[] {x,y}) ;
        while(!stack.isEmpty()){
            int [] temp = stack.pop() ;
            for( int k = 0; k < 4; k ++){
                int x1 = temp[0] + dx[k], y1 = temp[1] + dy[k];
                if( x1 >= 0 && x1 < grid.length && y1 >= 0 && y1 < grid[0].length ){
                    if(grid[x1][y1] == 1){
                        stack.push(new int[] {x1,y1}) ;
                        grid[x1][y1] = 2;
                    }
                    if(grid[x1][y1] == 0){
                       count ++ ;
                    }  
                } else { // 边界
                    count ++ ;
                }
            }
        }
        return count ;
    }
}

BFS

代码结构

	BFS(输入数据:矩阵或链表或树,起始点){
		建队列
		存储访问过节点tag: Map 或 改变输入数据 , 最短路径使用tag矩阵
		while( 队列不为空 ) {
			访问队头,poll()
			for(从队头出发访问,所有下一个节点(状态))
				if (如果没有访问 或 合法)
					加入队,访问:加入seen或改变输入数据
                      if(到达终点)返回
		}
	}

542. 01 矩阵

public class Solution {
	public static void main(String[] args) {
		int [][] matrix = new int[][] {{1,0,0},{1,1,1},{1,1,1}} ;
		updateMatrix(matrix) ;
	}
    public static int[][] updateMatrix(int[][] matrix) {
    	int[][] result = new int[matrix.length][matrix[0].length] ;
    	int[] dx = new int [] {0,-1,0,1} ;
    	int[] dy = new int [] {-1,0,1,0} ;
    	for( int i = 0; i < matrix.length; i ++) {
    		for ( int j = 0; j < matrix[0].length; j ++) {
    			if( matrix[i][j] == 0) {
    				result[i][j] = 0 ;
    			} else {
    				BFS(matrix, result,dx,dy,i,j) ;
    			}
    			
    		}
    	}
    	
    	return result ;
    }
    public static void BFS(int[][] matrix, int[][] result, int[] dx, int[] dy, int x, int y) {
    	Queue<Integer[]> queue = new LinkedList<Integer[]>() ; 
    	int[][] tag =new int[matrix.length][matrix[0].length];
    	queue.add(new Integer[] {x,y}) ;

    	while(!queue.isEmpty()) {
    		Integer[] temp = queue.poll() ;
    		int x1 = temp[0], y1 = temp[1] ;
    		for(int d = 0; d < 4; d ++) {
    			int i = x1 + dx[d], j = y1 + dy[d] ;
    			if(i>=0 && i < matrix.length && j>=0 && j < matrix[0].length && tag[i][j] == 0) {
  
    				queue.add(new Integer[] {i,j}) ;
    				tag[i][j] = tag[x1][y1] + 1 ;
    				
      				if(matrix[i][j] == 0) { // 找到
    					result[x][y] = tag[i][j]  ;
    					return ;
    				}
    			}
    		}
    	}
    }
}

102. 二叉树的层序遍历

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>() ;
        if(root == null) {
    		return result  ;
    	}
    	BFS(root,result) ;
    	return result ;
    }
    public static void BFS(TreeNode root, List<List<Integer>> result) {
    	Queue<TreeNode> queue = new LinkedList<TreeNode>() ;
    	queue.add(root) ;
    	while(!queue.isEmpty()) {
    		int len = queue.size() ;
    		List<Integer> temp = new ArrayList<Integer>() ;
    		for (int i = 0; i < len; i++) { // 当前层数据全部出完
    			TreeNode node = queue.poll() ;
    			temp.add(node.val) ;
        		if( node.left != null) {
        			queue.add(node.left) ;
        		}
        		if( node.right != null) {
        			queue.add(node.right) ;
        		}
    		}
    		result.add(temp) ;
    	}
    }
}

待更.....

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值