• qinggeouye
    2019-02-24
    # 思考题 python
    import getpass
    import os
    import queue


    def bfs_dir(path):
        """
        广度优先搜索:在给定路径下,搜索文件或子目录,
        子目录需要进一步搜索其下的文件和子目录,直到没有更多的子目录
        :param path: 给定目录的路径
        :return:
        """
        # 给出的路径是否是一个目录
        if not os.path.isdir(path):
            return
        que = queue.Queue()
        visited = set()
        for p in os.listdir(path):
            bfs_path = path + os.sep + p
            if os.path.isdir(bfs_path):
                que.put(bfs_path)
                visited.add(bfs_path)
                print('文件夹\t', bfs_path)
            else:
                print('文件\t', bfs_path)
        while not que.empty():
            cur_path = que.get()
            if len(os.listdir(cur_path)) == 0:
                continue
            for p in os.listdir(cur_path):
                bfs_path = cur_path + os.sep + p
                if bfs_path in visited:
                    continue
                if os.path.isdir(bfs_path):
                    que.put(bfs_path)
                    visited.add(bfs_path)
                    print("文件夹\t", bfs_path)
                else:
                    print("文件\t", bfs_path)


    if __name__ == "__main__":
        dir_path = ''
        user = getpass.getuser() # 计算机当前登陆用户
        if os.name == "posix": # Unix 或 OS X 操作系统
            dir_path = '/Users/' + user + '/Desktop/GeekTime/MathematicProgrammer'
        elif os.name == "nt": # Win 操作系统
            dir_path = '\\Users\\' + user + '\\Desktop\\GeekTime\\MathematicProgrammer'
        bfs_dir(dir_path)
    展开
    
     3
  • Joe
    2019-01-20
    C++实现DFS显示ubuntu指定目录下所有的文件,请老师指点。
    #include <dirent.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <iostream>
    #include <regex>
    #include <stack>
    using namespace std;

    class FileSearch {
      private:
      stack<string> path; // 路径栈

      public:
      /**
       * Detail: DFS显示ubuntu指定目录下文件
       * basePath- 文件路径
       * return: null
       */
      void DfsFile(char *basePath) {
        DIR *dir;
        struct dirent *ptr;
        char base[1000];
        char temp[1000];
        // 路径入栈
        path.push(basePath);
        // 遍历开始
        while (!path.empty()) {
          // 打开当前目录
          strcpy(temp, path.top().c_str());
          path.pop();
          cout << "Current path: " << temp << endl;
          if ((dir = opendir(temp)) == NULL) {
            perror("Open dir error, please input the right path");
            exit(1);
          }
          // 显示当前路径下的文件
          while ((ptr = readdir(dir)) != NULL) {
            // 忽略隐藏文件和路径: .and..
            if (regex_match(ptr->d_name, regex("\\.(.*)"))) {
              continue;
            }
            if (ptr->d_type == 8) {
              // A regular file
              //cout << "file: " << basePath << "/" << ptr->d_name << endl;
              cout << ptr->d_name << endl;
            } else if (ptr->d_type == 4) {
              // 检测为文件夹
              memset(base, '\0', sizeof(base));
              strcpy(base, temp);
              strcat(base, "/");
              strcat(base, ptr->d_name);
              path.push(base);
              continue;
            }
          }
        }
        // 关闭文件
        closedir(dir);
      }
    };
    int main(void) {
      FileSearch test;
      // 需要遍历的文件夹目录
      char basePath[] = {"/home/joe/Desktop/leetcode"};
      test.DfsFile(basePath);
      return 0;
    }
    // 大致输出结果为:
    Current path: /home/joe/Desktop/leetcode
    leetcodePractice.cpp
    a.out
    README.md
    Current path: /home/joe/Desktop/leetcode/math_fundamental_algorithms
    recursion.cpp
    tree_depth_first_search.cpp
    recursion_integer.cpp
    permutation.cpp
    dynamic_programming.md
    iteration_way.cpp
    tree_breadth_first_search.md
    a.out
    tree_breadth_first_search.cpp
    math_induction.cpp
    byte_operation.cpp
    ......
    展开

    作者回复: 注意到了隐藏路径和文件的处理,很棒

    
     2
  • strentchRise
    2019-01-11
    自己代码功力不行,尽力写一个python版本的

    class Node:
        def __init__(self, number):
            self.num = number
            self.nodes = []

        def setNode(self, num):
            if(self.nodes.__contains__(num) == False):
                node = Node(num)
                self.nodes.append(node)
                return node
            else:
                return None

        def setNodeUnder(self, num, base):
            if (self.num == num):
                return self.setNode(num)

            baseNode = self.get(base, self.nodes)
            if baseNode == None:
                return None
            else:
                return baseNode.setNode(num)

        def get(self, num, nodes=None):
            if(self.nodes == None or len(nodes) == 0):
                return None
            else:
                someNodes = []
                for node in nodes:
                    if node.num == num:
                        return node
                    for n in node.nodes:
                        someNodes.append(n)
                return self.get(num, someNodes)
        
        def search(self):
            print(self.num)
            self.printNodes(self.nodes)

        def printNodes(self, nodes=None):
            if nodes == None or len(nodes) == 0:
                return
            else:
                someNodes = []
                for node in nodes:
                    print(node.num)
                    for n in node.nodes:
                        someNodes.append(n)
                return self.printNodes(someNodes)

    root = Node(110)
    root.setNode(123)
    root.setNode(879)
    root.setNode(945)
    root.setNode(131)
    root.setNodeUnder(162, 123)
    root.setNodeUnder(587, 123)
    root.setNodeUnder(580, 945)
    root.setNodeUnder(762, 945)
    root.setNodeUnder(906, 131)
    root.setNodeUnder(681, 587)

    root.search()

    output:
    110
    123
    879
    945
    131
    162
    587
    580
    762
    906
    681
    finish...
    展开

    作者回复: 很好的还原了原文的示例👍

    
     1
  • escray
    2020-02-03
    回过头来重看了一遍,对于树的广度优先搜索,从概念上理解了,但是实际动手写一段 Java 或者是 Python 的代码,还是没有信心。

    学习了 @qinggeouye 的 Python 代码 和 @恬毅 的 Java 代码。希望以后自己也能提交一些代码。

    作者回复: 反复学习,坚持就可以

    
    
  • 唔多志
    2020-01-28
    第二,广度优先搜索也可以让我们访问所有和起始点相通的点,因此也被称为广度优先遍历。如果一个图包含多个互不连通的子图,那么从起始点开始的广度优先搜索只能涵盖其中一个子图。这时,我们就需要换一个还没有被访问过的起始点,继续深度优先遍历另一个子图。深度优先搜索可以使用同样的方式来遍历有多个连通子图的图,这也回答了上一讲的思考题。

    "这时,我们就需要换一个还没有被访问过的起始点,继续深度优先遍历另一个子图。"中的继续深度优先遍历另一个子图,这里是不是有问题啊?应该是继续广度优先遍历?不然感觉很矛盾啊。

    作者回复: 对 是笔误 应该是继续广度优先

    
    
  • cwtxz
    2019-12-31
    编程这么些年,就从来没有把递归相关的编程问题克服过。虽然天天加班,但是一直都在做一些重复的业务,遇到一些稍微麻烦的问题,下意识的就会去网上搜索现成的解决方案,久而久之,自己独立分析思考问题的能力变得羸弱不堪。一旦遇到一些稍微抽象一点、分析步骤稍微繁琐的问题,往往找不到破解问题的方向,坚持不了多久就容易心浮气躁,心生放弃。所以,类似递归这类抽象度高又复杂的算法,本能地会畏惧,敬而远之。但是,男人不能怂,这次我不能避而不战了,我一定要克服递归,无论多难,我都不想放弃!!!加油!!!

    作者回复: 相信你可以做到的,新年新气象👍

    
    
  • 建强
    2019-12-21
    简单用Python写了一个程序:
    # 用深搜和广搜列出目录
    import os

    # 深搜列目录
    def dls(path,level):
    #BEGIN

        for file in os.listdir(path):

            # 如果是子目录,则递归访问该子目录
            if os.path.isdir(file):
                print('-' * level * 2, '子目录:{}'.format(file))
                dls(path + '/' + file, level + 1)
            else:
                print('-' * level * 2, '文件名:{}'.format(file), '-'*10)
    #END


    # 广搜列目录
    def bls(path):
    #BEGIN
        level = 0

        #创建并初始化队列
        queue = []
        queue.append((path,level))


        # 队列不空时,取出队列中的元素进行遍历
        while len(queue) > 0:
            subpath = queue[0][0]
            level = queue[0][1]
            queue.remove(subpath)

            print('-' * level * 2, '{}下的所有文件:'.format(subpath), '-' * level * 2)

            for file in os.listdir(subpath):

                # 如果是子目录仍然进队列
                if os.path.isdir(file):
                    print(' ' * (level + 1) * 2, '子目录:{}'.format(file))
                    queue.append((subpath + '/' + file, level + 1))
                else:
                    print(' ' * (level + 1) * 2, '文件名:{}'.format(file))
    #END

    # 主程序
    def main():
    #BEGIN
        print('深度优先搜索目录:C:\')
        dls('c:/', 1)
        print('广度优先搜索目录:C:\')
        bls('c:/')
    #END


    if __name__ == '__main__':
        main()
    展开
    
    
  • Paul Shan
    2019-08-23
    树的广度优先是从根开始,从上到下,按层遍历,每一层,按照从左到右遍历,如果把结果排出来,也就是按两个维度排序,层次是第一优先级,左右是第二优先级。实现中用队列。

    二叉树的深度遍历有两个顺序,一个顺序是节点被发现的顺序,另外一个是节点完成的顺序。被发现的顺序和树的前序遍历一致,中左右递归进行。完成的顺序和树的后序遍历一致,左右中递归进行。实现中用栈。
    
    
  • 恬毅
    2019-08-22
    package package13;

    import java.util.HashSet;
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Stack;

    public class File {
        public String name;
        public HashSet<File> children;
        public String parent;
        
        public String getPath() {
            if (name == null)
                return null;
            if (parent == null) {
                return this.name;
            }
            return this.parent.concat("/").concat(this.name);
        }
        
        public File(String name, String parent) {
            this.name = name;
            this.parent = parent;
            this.children = new HashSet<File>();
        }
        
        public static void addFile(File file, String path) {
            String[] arr = path.split("/");
            boolean exist = false;
            File newFile = null;
            for (File files : file.children) {
                if (files.name.equals(arr[0])) {
                    exist = true;
                    newFile = files;
                }
            }
            if (!exist) {
                newFile = new File(arr[0], file.getPath());
                file.children.add(newFile);
            }
            if (arr.length > 1) {
                addFile(newFile, path.substring(path.indexOf("/") + 1));
            }
        }
        
        public static void guangdu(File file) {
            Queue<File> queue = new LinkedList<File>();
            queue.offer(file);
            while(!queue.isEmpty()) {
                File iterator = queue.poll();
                System.out.println(iterator.getPath());
                for (File child : iterator.children) {
                    queue.offer(child);
                }
            }
        }
        
        public static void shendu(File file) {
            Stack<File> stack = new Stack<File>();
            stack.push(file);
            while(!stack.isEmpty()) {
                File iterator = stack.pop();
                System.out.println(iterator.getPath());
                for (File child : iterator.children) {
                    stack.push(child);
                }
            }
        }
        
        public static void main(String[] args) {
            File file = new File(null, null);
            addFile(file, "d:/a/b/c");
            addFile(file, "d:/a/b/c");
            addFile(file, "d:/a/b/d");
            addFile(file, "d:/a/b2/d");
            addFile(file, "d:/a/b3/d");
            addFile(file, "d:/b/b3/d");
    //        shendu(file);
            guangdu(file);
        }
    }
    展开
    
    
  • 蜉蝣
    2019-01-28
    老师你好。请问这句话是什么意思:“这时,我们就需要换一个还没有被访问过的起始点,继续深度优先遍历另一个子图。” 为什么换了一个起始点之后就要用深度优先遍历呢?

    作者回复: 这里是一个笔误,应该是继续“广度”优先。我稍后改一下

    
    
  • 菩提
    2019-01-16
    我好好检查了一下我的代码逻辑,您的逻辑是正确的。

    我这边visited集合没有把user_id加入,导致的问题。

    控制台的输出日志。我查询的是user_id是 0, 而控制台打印了一行记录是 2度好友:0 。 出现这个打印的原因是遍历0的好友。该好友的friends包含了0,在for循环中算了user_id=0的情况。

    谢谢老师指正!
    展开

    作者回复: 找到问题就好👍

    
    
  • 菩提
    2019-01-15
    广度优先搜索那块有2个小瑕疵,您看一下。
    1. 防止数组越界的异常,user_id 等于数组长度也会越界。
    2.遍历子节点的时候,如果子节点friends中存在需要查询的user_id,则出现错误的打印输出。如果是查询的user_id应该continue。

    控制台打印
    0:[3]:0
    1:[3]:0
    2:[3]:0
    3:[0, 1, 2, 4]:0
    4:[3]:0
        1 度好友:3
        2 度好友:0
        2 度好友:1
        2 度好友:2
        2 度好友:4

    代码如下,
        public static Node[] init(int user_num, int relation_num) {
            Random rand = new Random();

            Node[] user_nodes = new Node[user_num];

            // 生成所有表示用户的节点
            for (int i = 0; i < user_num; i++) {
                user_nodes[i] = new Node(i);
            }

            // 生成所有表示好友关系的边
            for (int i = 0; i < relation_num; i++) {
                int friend_a_id = rand.nextInt(user_num);
                int friend_b_id = rand.nextInt(user_num);
                if (friend_a_id == friend_b_id)
                    continue;
                Node friend_a = user_nodes[friend_a_id];
                Node friend_b = user_nodes[friend_b_id];
                friend_a.friends.add(friend_b_id);
                friend_b.friends.add(friend_a_id);
            }

            return user_nodes;
        }

        public static void bfs(Node[] user_nodes, int user_id) {
            // 防止数组越界异常
            if (user_id >= user_nodes.length)
                return;

            // 用于广度优先搜索的队列
            Queue<Integer> queue = new LinkedList<>();

            // 放入初始节点
            queue.offer(user_id);

            // 存放已经被访问过的节点,防止回路
            HashSet<Integer> visited = new HashSet<>();

            while (!queue.isEmpty()) {
                // 取出队列头部的第一个节点
                int current_user_id = queue.poll();
                if (user_nodes[current_user_id] == null)
                    continue;

                // 遍历刚刚拿到的这个节点的所有直接连接节点,并加入队列尾部
                for (int friend_id : user_nodes[current_user_id].friends) {
                    if (user_nodes[current_user_id] == null)
                        continue;
                    if (visited.contains(friend_id))
                        continue;
                    queue.offer(friend_id);
                    // 记录已经访问过的节点
                    visited.add(friend_id);
                    // 好友度数是当前节点的好友度数再加1
                    user_nodes[friend_id].degree = user_nodes[current_user_id].degree + 1;
                    System.out.println(String.format("\t%d 度好友:%d", user_nodes[friend_id].degree, friend_id));
                }
            }
        }

        public static void main(String[] args) {
            Node[] user_nodes = init(5, 8);
            for (Node d : user_nodes) {
                System.out.println(d.user_id + ":" + d.friends + ":" + d.degree);
            }
            bfs(user_nodes, 0);
        }
    展开

    作者回复: 第一点是很好的发现,我稍后加一下。
    第二点没有看太明白,能否补充说明一下?

    
    
  • Being
    2019-01-11
    使用C++的双端队列deque实现的BFS和DFS
    namespace FilePathOperator {
        struct St_FilePathNode;
        typedef std::set<St_FilePathNode*> SetterFilePathNode;
        typedef void(*FilPathOperator)(const St_FilePathNode& rStFilePathNode);
        typedef struct St_FilePathNode {
            int m_nLevel;
            std::string m_strFilePath;
            SetterFilePathNode m_setChildernPathNodes;
        }StFilePathNode;
    };
    void FilePathOperator::BFSFilePathNodes(StFilePathNode * pRoot, FilPathOperator nodeOperator, int nMaxLevel)
    {
        if (NULL == pRoot)
            return;

        std::deque<StFilePathNode*> queNode;
        queNode.push_front(pRoot);

        pRoot->m_nLevel = 0;    // Root Level is first one

        while (!queNode.empty())
        {
            StFilePathNode* pNode = queNode.back();
            queNode.pop_back();
            if (NULL == pNode) continue;
        
            int nNodeLevel = pNode->m_nLevel;
            nodeOperator(*pNode);

            if (nNodeLevel + 1 > nMaxLevel)    continue; // childern beyond MaxLevel

            SetterFilePathNode::iterator ChildItr = pNode->m_setChildernPathNodes.begin();
            for (; ChildItr != pNode->m_setChildernPathNodes.end(); ChildItr++) {
                if (NULL == *ChildItr)
                    continue;

                (*ChildItr)->m_nLevel = nNodeLevel + 1;
                queNode.push_front(*ChildItr);
            }
        }
    }
    void FilePathOperator::DFSFilePathNodes(StFilePathNode * pRoot, FilPathOperator nodeOperator, int nMaxLevel)
    {
        if (NULL == pRoot)
            return;

        std::deque<StFilePathNode*> deqNode;
        deqNode.push_front(pRoot);

        pRoot->m_nLevel = 0;    // Root Level is first one

        while (!deqNode.empty())
        {
            StFilePathNode* pNode = deqNode.front();
            deqNode.pop_front();
            if (NULL == pNode) continue;

            int nNodeLevel = pNode->m_nLevel;
            nodeOperator(*pNode);

            if (nNodeLevel + 1 > nMaxLevel)    continue; // childern beyond MaxLevel

            SetterFilePathNode::iterator ChildItr = pNode->m_setChildernPathNodes.cbegin();
            for (; ChildItr != pNode->m_setChildernPathNodes.cend(); ChildItr++) {
                if (NULL == *ChildItr)
                    continue;

                (*ChildItr)->m_nLevel = nNodeLevel + 1;
                deqNode.push_front(*ChildItr);
            }
        }
    }
    (其他的Create、Destroy、Print就暂时不贴出来了)
    展开

    作者回复: Deque确实是个好东西,只是名字有时让人联想不到stack :)

    
    
我们在线,来聊聊吧