关闭

编程之美1.14连连看游戏设计-----广度优先算法Java版

295人阅读 评论(0) 收藏 举报
分类:
代码从网上找的,稍微改了改。
第一遍学习先学到这些吧
public class BFS {

    public static class Queue {

        public int Depth;
        public int Dot;

        Queue() {
            Depth = -1;
            Dot = -1;
        }

        public void enterQueue(int dot, int dep) {
            Dot = dot;
            Depth = dep;
            System.out.println(Dot + " " + "The Depth is:" + Depth);
        }

        public int depDate() {
            return Depth;
        }

        public int dotdate() {
            return Dot;
        }
    };

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] Graph = {{0, 1, 0, 0, 1, 0, 0, 0, 0, 0},
        {1, 0, 1, 1, 0, 0, 0, 0, 0, 0},
        {0, 1, 0, 0, 0, 0, 1, 0, 0, 0},
        {0, 1, 0, 0, 1, 1, 0, 0, 0, 0},
        {1, 0, 0, 1, 0, 0, 0, 0, 1, 0},
        {0, 0, 0, 1, 0, 0, 1, 1, 0, 0},
        {0, 0, 1, 0, 0, 1, 0, 0, 0, 1},
        {0, 0, 0, 0, 0, 1, 0, 0, 1, 1},
        {0, 0, 0, 0, 1, 0, 0, 1, 0, 0},
        {0, 0, 0, 0, 0, 0, 1, 1, 0, 0},};
        boolean[] vis = new boolean[Graph.length];
        Arrays.fill(vis, false);

        Queue[] queue = new Queue[Graph.length];
        for (int i = 0; i < 10; i++) {
            queue[i] = new Queue();
        }
       BFS1(queue, Graph, vis);
        
    }

    /*
     可以实现一个起点无法遍历全部节点时的情况
     */

    public static void BFS1(Queue[] queue, int[][] Graph, boolean[] vis) {
        int base = 0;
        int top = 0;
        for (int i = 0; i < Graph.length; i++) {
            if (vis[i] == false) {
                queue[top].enterQueue(i, 1);
                top++;
                vis[i] = true;
                while (top != base) {
                   int dep = queue[base].depDate() + 1;
                   int dot = queue[base].dotdate();
                    for (int j = 0; j < 10; j++) {
                        if (Graph[dot][j] == 1 && vis[j] == false) {
                            queue[top].enterQueue(j, dep);
                            top++;
                            vis[j] = true;
                        }
                    }
                    base++;
                }
            }
        }
    }
}

0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4971次
    • 积分:307
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类