搜索
深度搜索:
使用递归方法 试探与回溯
在递归函数中,
- 先判断是否为终点,如是则输出
- 循环每个子节点,是否越界
- 是否被访问
- 满足条件的,
4.1 标记当前点已被访问
4.2 递归子节点
4.3 回溯该节点未被访问
public class Main {
static int endx=4;static int endy=4;
static int min_step=99;
static int n=4,m=4;
static int[][] direction = {{0, -1}, {-1, 0},{0, 1}, {1, 0}};//方向向量
static int result[][]={
{0,1,0,0,1},
{0,0,0,1,0},
{1,0,0,0,1},
{0,0,0,0,0},
{1,0,0,0,0}
};// result是二维数组用于标记点是否访问,是全局类型,其中1也可以表示障碍物,需绕道前行
static char[] buz=new char[100];
public static void main(String[] args) {
dfs(0, 0, 0);
System.out.println(min_step);
}
public static void dfs(int x,int y,int step) {
if(endx==x && endy==y){ // 判断是否到了终点
System.out.println(String.valueOf(buz));//到终点的路径
if(step < min_step){ // 判断是否为最小步数
min_step = step;
}
return; // 返回
}
for(int i = 0 ; i<4;i++){
// 计算下一个点的坐标
int next_x = x + direction[i][0];
int next_y = y + direction[i][1];
buz[step]=(char) (i+'0');//保存路径
// 需要判断下一个点是否越界,有可能超出了边界
// n是数组的行,m是数组的列
if (next_x < 0 || next_x > n || next_y < 0 || next_y > m) {
continue;
}
if (result[next_x][next_y] == 0) {// 判断当前点是否访问
result[next_x][next_y] = 1; // 标记当前点访问
dfs(next_x, next_y, step + 1); // 另一个点继续递归
result[next_x][next_y] = 0; // 标记当前点未访问,基于上一步的递归结束
}
}
}
}
BFS
需要一个结构体(java中是类)来储存每个节点的信息,使用队列数据结构
- 创建节点类
- 创建节点队列
- 起点(根节点)进入队列
- 当队列中有元素时进行循环
4.1 根节点出队
4.2 for 循环 判断下一个节点是否越界,是否已被访问,是否有障碍物,是则continue
4.3 满足条件子节点入队
class Node{
int x ;
int y ;
Node parent;
}
public class Main {
static int endx=4;static int endy=4;
static int min_step=99;
static int n=4,m=4;
static int[][] direction = {{0, -1}, {-1, 0},{0, 1}, {1, 0}};//方向向量
static int result[][]={
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};// result是二维数组用于标记点是否访问,是全局类型,其中1也可以表示障碍物,需绕道前行
static int map[][]={
{0,1,0,0,1},
{0,0,0,1,0},
{1,0,0,0,1},
{0,0,0,0,0},
{1,0,0,0,0}
};
static char[] buz=new char[100];
public static void main(String[] args) {
//dfs(0, 0, 0);
//System.out.println(min_step);
class Node{
int x ;
int y ;
int step;
String lujingString="";
}
// 设置队列
LinkedList<Node> que=new LinkedList<Node>();
//起点进队列
Node node = new Node();
node.x = 0;
node.y = 0;
node.step = 0;
que.add(node);// 起始点进队列
// 将起点的周围的点进队列
while(que.size()!=0) {
//注意这里不能用que!=null
Node root=que.poll();
for (int i = 0; i < 4; i++) {
int tx = root.x + direction[i][0];
int ty = root.y + direction[i][1];
// 判断是否越界
if (tx < 0 || tx > n || ty < 0 || ty > m) {
continue;
}
// 判断该点是否为障碍物并且有没有被访问
if (map[tx][ty] == 0 && result[tx][ty] == 0) {
Node next = new Node();
result[tx][ty] = 1;
next.x = tx;
next.y = ty;
next.step = root.step + 1;
next.lujingString=root.lujingString+i;
System.out.println("("+tx+","+ty+")");
que.add(next);// 进队列
}
// 如果当前点为最终节点
if (tx == endx && ty == endy) {
Node hh=que.getLast();
System.out.println(hh.lujingString);
}
}
}
}
}