为了切换到java的熟练状态,然后今天也开始了自我锻炼,下面是使用队列实现广度优先搜索的算法 好了 我们直接进入下面主题。
下面就来讲述我来总结我的实现思路总结。
- 明白其实现思想。
- 思考用什么数据结构方式来进行实现
- 开始我们的编程
思想
广度优先搜索就是将我们一开始的启始点的位置附近的临近点都进行遍历,把他们都加进我们的队列中去,然后在把起始点进行移除周而复始的进行操作,每次加入新的节点的时候,队列头就是新节点的父节点。
选择的数据结构
毫无疑问肯定就是对列了
开始我们的编程
案例: 如下图所示,当我们想要从(1,1)点移动到终点的时候 我们的最小路径是什么?
此时我们就可以用到我们刚刚学会的广度搜索来进行编写程序了
代码如下
public class width {
public Node head = new Node(0,0,0);
public Node tail = new Node(0,0,0);
class Node{
int x;
int y;
int step;
Node next ;
public Node(int x,int y,int step) {
this.x =x;
this.y = y;
this.step = step;
}
}
public static int[][] array = { { 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 0, 1 } };
public static int [][] direction = { {0,1} ,
{1,0} ,
{0,-1} ,
{-1,0} } ;
public static int[][] book = new int[5][4];
public void dfs() {
head.next = tail;
while(head!=null) {
for(int i = 0;i<4;i++) {
int tempx = head.x + direction[i][0];
int tempy = head.y + direction[i][1];
if(tempx<0 || tempx > 4 || tempy < 0||tempy > 3) {
continue;
}
if(book[tempx][tempy]==0&&array[tempx][tempy]!=1) {
Node node = new Node(tempx,tempy,head.step+1);
if(tempx==3 && tempy==2) {
System.out.println(node.step);
return;
}
tail.next = node;
tail = node;
book[tempx][tempy]=1;
}
}
head = head.next;
}
}
public static void main(String[] arg) {
width width = new width();
width.dfs();
}
}
这里我使用了指针队列,好啦 今天就到这里了 欢迎大家的点评。