看了网上别人的代码。。。自己模仿着敲了一边
package 万能的搜索;
import java.util.LinkedList;
import java.util.Queue;
/*
* 从左上角到右下角,最短路径;
* 广度优先搜索
*
* */
public class BFS {
/***重要组成-方向****/
int[][] direct = {{-1,0},{1,0},{0,-1},{0,1}};//上下左右
/****重要组成-标记****/
int[][]book = new int[4][4];
/***待输入的数组****/
int[][] array={
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
public static void main(String[] args) {
new BFS().BFS();
}
/*****重要组成-封装数组点,用坐标表示位置****/
class Node{
int row;
int column;
int round;
Node(int row,int column,int round){
this.row = row;
this.column = column;
this.round = round;
}
}
public void BFS() {
//搜索的起始点
Node start = new Node(0,0,0);
/****重要组成-待搜索队列的每个对象都是接下来要搜索的值****/
Queue<Node> queue = new LinkedList<Node>();
queue.offer(start);
book[0][0] = 1;
while(queue.size()>0) {
//出队,对出队元素进行搜索
Node temp = queue.poll();
for(int i=0;i<4;i++) {
//确定下一个点的坐标
int tx = temp.row + direct[i][0];
int ty = temp.column + direct[i][1];
/*********排除不满足条件的********************/
// 检查越界
if(tx < 0 || ty<0 || tx>=4 || ty>=4)
continue;
//检查标记
if(book[tx][ty]==1)
continue;
/*********************************************/
// 之后就是满足条件的
Node next = new Node(tx,ty,temp.round+1);
book[tx][ty] = 1;
queue.offer(next);
System.out.println("数值:"+array[tx][ty]+",轮次:"+(temp.round+1));
}
}
}
}
结果如下:
数值:5,轮次:1
数值:2,轮次:1
数值:9,轮次:2
数值:6,轮次:2
数值:3,轮次:2
数值:13,轮次:3
数值:10,轮次:3
数值:7,轮次:3
数值:4,轮次:3
数值:14,轮次:4
数值:11,轮次:4
数值:8,轮次:4
数值:15,轮次:5
数值:12,轮次:5
数值:16,轮次:6