1,对于方格的回溯遍历
(1)控制方向使用基本方向数组: int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
(2)循环遍历取向:
for (int[] n : next)
if (backtracking(matrix, str, marked, pathLen + 1, r + n[0], c + n[1]))
return true;
其中 n[0]=0,0,-1,1 , n[1]=-1,1,0,0
这意味着每次对于行列只有一个方向是操作的,且同时满足四个方向上的移动(每次一个)。
(3)典型题目解析 剑指offer12:
2, 矩阵中的路径
题目描述:
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如下面的矩阵包含了一条 bfce 路径。
代码如下:
package come;
/**
* 矩阵中的路径问题(回溯法)--指定路径
* @author lzq
* @version 1.0
* @description
* @date 2019/7/31 21:33
*/
import java.util.*;
public class Main7 {
private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int rows;
private int cols;
public boolean hasPath(char[] array, int rows, int cols, char[] str)
{
if(cols==0||rows==0)
{
return false;
}
this.rows=rows;
this.cols=cols;
boolean[][] panduan=new boolean[rows][cols];
char[][] news=tochange(array);
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(backtrack(news,str,i,j,0,panduan))
{
return true;
}
}
}
return false;
}
public boolean backtrack(char[][] news,char[] str,int r,int c,int pathlen,boolean[][] panduan)
{
if(pathlen==str.length)
{
return true;
}
if(r<0||r>=rows||c<0||c>=cols||news[r][c]!=str[pathlen]||panduan[r][c])
{
return false;
}
panduan[r][c]=true;
for(int[] n:next)
{
if(backtrack(news,str,r+n[0],c+n[1],pathlen+1,panduan))
{
return true;
}
}
panduan[r][c]=false;
return false;
}
public char[][] tochange(char[] nums)
{
char[][] news=new char[rows][cols];
int index=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
news[i][j]=nums[index++];
}
}
return news;
}
}