深度优先搜索

realcj1990 2017-09-21 06:29:26
import java.io.*;
import java.util.*;

class Saver
{
public Saver(int[][] graph, int startX, int startY, int targetX, int targetY)
{
this.graph = graph;
this.startX = startX;
this.startY = startY;
this.targetX = targetX;
this.targetY = targetY;
this.minLength = 99999999;
directions = new int[][]{ { 0, 1 } , { 1, 0 }, { 0, -1 }, { -1, 0 } };
}

public void dfs()
{
boolean[][] explored = new boolean[graph.length][graph[0].length];
explored[startX][startY] = true;
dfs(startX, startY, 0, explored);
}

public int getMinLength()
{
return minLength;
}

private void dfs(int x, int y, int steps, boolean[][] explored)
{
if (x == targetX && y == targetY)
{
if (steps < minLength)
{
minLength = steps;
return;
}
}

for (int k = 0; k < directions.length; k++)
{
int next_x = x + directions[k][0];
int next_y = y + directions[k][1];

if (next_x < 0 || next_x > graph.length - 1 || next_y < 0 || next_y > graph[0].length - 1)
{
continue;
}

if (graph[next_x][next_y] == 0 && !explored[next_x][next_y])
{
explored[next_x][next_y] = true;
dfs(next_x, next_y, steps + 1, explored);
// 为什么这里要取消这个标志,置为false
explored[next_x][next_y] = false;
}
}
}

private int[][] graph;
private int startX;
private int startY;
private int targetX;
private int targetY;
private int[][] directions;
private int minLength;

public static void main(String[] args)
{
try
{
Scanner in = new Scanner(new File("data.txt"));
int m = in.nextInt();
int n = in.nextInt();
int[][] graph = new int[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
graph[i][j] = in.nextInt();
}
}
int startX = in.nextInt();
int startY = in.nextInt();
int targetX = in.nextInt();
int targetY = in.nextInt();

Saver saver = new Saver(graph, startX, startY, targetX, targetY);
saver.dfs();
System.out.println("Shortest length to save lil ha is " + saver.getMinLength());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}

// 数据
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
0 0 3 2

5 4 是图的行,列数,最后一行是起点坐标(0,0)和目标坐标(3,2),问从起点到终点的最短长度
为什么在dfs()递归后面要写explored[next_x][next_y] = false
...全文
169 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wallesyoyo 2017-09-22
  • 打赏
  • 举报
回复
表示这个点搜索过了呀,避免递归时候死循环无限递归啊,还有你这也不是C++啊,发错区了吧兄弟。

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧