标签:回溯法 style 图片 str public 记录 越界 题记 bool
用递归实现回溯法
注意:对于越界的检查是row>=matrix.length和col>=matrix[0].length要加上等号(这个错误找了半个小时呜呜呜)
public class Solution { private int[][] act = {{0,1},{0,-1},{-1,0},{1,0}}; public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { if(matrix.length==0) return false; char[][] array = makematrix(matrix, rows, cols); boolean[][] marked = new boolean[rows][cols]; int pathlen = 0; for(int i = 0; i<rows; i++){ for(int j = 0;j<cols;j++){ if(backtrack(array, marked, str, pathlen,i, j)) return true; } } return false; } public boolean backtrack(char[][] matrix, boolean[][] marked, char[] str, int pathlen, int row, int col){ if(pathlen == str.length) return true; if(row<0||row>=matrix.length||col<0||col>=matrix[0].length||marked[row][col]||matrix[row][col]!=str[pathlen]) return false; pathlen++; marked[row][col] = true; for(int[] n: act){ if(backtrack(matrix, marked, str, pathlen,row+n[0], col+n[1])) return true; } marked[row][col] = false; return false; } public char[][] makematrix(char[]matrix, int row, int col){ char[][] array = new char[row][col]; for(int i = 0, idx = 0; i<row; i++){ for(int j = 0; j<col; j++){ array[i][j] = matrix[idx++]; } } return array; } }
标签:回溯法 style 图片 str public 记录 越界 题记 bool
原文地址:https://www.cnblogs.com/tendermelon/p/12827139.html