java之广度优先搜索

 

为了切换到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();	
	}
}

 

这里我使用了指针队列,好啦 今天就到这里了 欢迎大家的点评。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值