矩阵中的路径(注释详细,可作为模板)--深度优先遍历dfs

题目描述

在这里插入图片描述

代码

class Solution {
    
    
    public boolean exist(char[][] board, String word) {
    
    
        
        //将string转换成字符数组
        char[] words = word.toCharArray();
        
        //从i,j处开始遍历
        for(int i = 0;i < board.length; i++){
    
    
            for(int j = 0;j < board[0].length;j++){
    
    
                if(dfs(board,words,i,j,0)){
    
    
                    return true;
                }
            }
        }
        return false;
    }

	//参数列表(二维数组,给定字符数组,起始i,起始j,字符数组索引)
    public boolean dfs(char[][] board,char[] words,int i,int j,int index){
    
    
    
        //判断边界条件
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != words[index]){
    
    
            return false;
        }

		//判断字符数组是否遍历完
        if(index == words.length - 1){
    
    
            return true;
        }
		
		//暂存二维数组遍历位置的值,保证只遍历一次
        char temp = board[i][j];
        board[i][j] = '.';
		
		//依次遍历上,下,左,右
        boolean res = dfs(board,words,i-1,j,index+1) ||
                      dfs(board,words,i+1,j,index+1) ||
                      dfs(board,words,i,j-1,index+1) ||
                      dfs(board,words,i,j+1,index+1);
		
		//遍历完成,恢复二维数组的值
        board[i][j] = temp;
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44809329/article/details/113914385