public class pathMatrix { public static boolean hasPath(char[][] matrix,int rows,int columns,String str,int totalLength){ //如果传入值为空 if(matrix==null||rows<1||columns<1||str==null){ return false; } //标记函数,初始化为false Boolean[][] visited = new Boolean[rows][columns]; for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ visited[i][j]=false; } } //路径长度 int pathLength=0; // for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ if(hasPathCore(matrix,rows,columns,i,j,str,pathLength,visited,totalLength)){ return true; } } } return false; } public static Boolean hasPathCore(char[][] matrix,int rows,int columns,int row,int column,String str,int pathLength,Boolean[][] visited,int totalLength){ if(pathLength>=totalLength){ return true; } Boolean hasPath=false; if(row>=0&&row<rows&&column>=0&&column<columns&&matrix[row][column]==str.charAt(pathLength)&&!visited[row][column]){ ++pathLength; visited[row][column]=true; hasPath=hasPathCore(matrix,rows,columns,row,column-1,str,pathLength,visited,totalLength)||hasPathCore(matrix,rows,columns,row,column+1,str,pathLength,visited,totalLength)||hasPathCore(matrix,rows,columns,row-1,column,str,pathLength,visited,totalLength)||hasPathCore(matrix,rows,columns,row+1,column,str,pathLength,visited,totalLength); if(!hasPath){ --pathLength; visited[row][column]=false; } } return hasPath; } public static void main(String[] args){ char[][] matrix={{'a','b','t','g'},{'c','f','c','s'},{'j','d','e','h'}}; String str="bfce"; int rows=matrix.length; int columns=matrix[0].length; int totalLength=str.length(); System.out.println(hasPath(matrix,rows,columns,str,totalLength)); } }
理解了上面这题在做下面这题就容易多了
public class robotMove { public static Boolean permitMove(int row,int column,int k){ int r=row,c=column; int ans=0; while(r!=0){ ans=ans+r%10; r/=10; } while(c!=0){ ans=ans+c%10; c/=10; } if(k>=ans){ return true; } else{ return false; } } public static void move(int[][] visited,int m,int n,int row,int column,int k){ if(row>=0&&row<m && column>=0&&column<n && visited[row][column]==0 && permitMove(row,column,k)){//当这个格子可以走 visited[row][column]=1; move(visited,m,n,row-1,column,k); move(visited,m,n,row+1,column,k); move(visited,m,n,row,column-1,k); move(visited,m,n,row,column+1,k); } else{ return; } } public static int countPlace(int[][] visited,int m,int n){ int count=0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(visited[i][j]==1){ count++; } } } return count; } public static void main(String[] args){ Scanner input = new Scanner((System.in)); int m = input.nextInt(); int n = input.nextInt(); int k = input.nextInt(); int[][] visited=new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ visited[i][j]=0; } } int count=0; int row=0,column=0; move(visited,m,n,row,column,k); System.out.println(countPlace(visited,m,n)); } }