"Sword Finger Offer" Path in the matrix (Java)

Title description

Insert picture description here

AC code

public class Solution {
    char[] matrix;
    char[] str;
    public boolean hasPath(char[] _matrix, int rows, int cols, char[] _str)
    {
        matrix=_matrix;
        str=_str;
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(dfs(rows,cols,0,i,j))
                    return true;
            }
        }
        return false;
    }
    
    boolean dfs(int rows,int cols,int u,int x,int y){
        int pos=x*cols+y;
        if(matrix[pos]!=str[u])
            return false;
        if(u==(str.length-1))
            return true;
        char tmp=matrix[pos];
        //说明访问过
        matrix[pos]='*';
        //定义方向
        int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
        for(int i=0;i<4;i++){
            int a=x+dx[i],b=y+dy[i];
            if(a>=0&&a<rows&&b>=0&&b<cols)
                if(dfs(rows,cols,u+1,a,b))
                    return true;
        }
        matrix[pos]=tmp;
        return false;
    }


}
Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/104349321
Recommended