Giter Club home page Giter Club logo

Comments (1)

pezy avatar pezy commented on August 24, 2024

BFS in sorted way.

#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <deque>
#include <string>
#include <sstream>

void printUndirectedGraph(UndirectedGraphNode *node) {
    std::ostringstream out;
    std::unordered_map<int, std::unordered_set<int>> map{{0, std::unordered_set<int>()}};
    std::deque<UndirectedGraphNode*> cache;
    cache.push_back(node);
    do {
        std::sort(cache.begin(), cache.end(),[](UndirectedGraphNode* n1, UndirectedGraphNode* n2){
            return n1->label < n2->label;
        });
        UndirectedGraphNode *node = cache.front(); cache.pop_front();
        out << node->label;
        auto found = map.find(node->label);
        for (UndirectedGraphNode* neighbor : node->neighbors) {
            if (map.find(neighbor->label) == map.end()) cache.push_back(neighbor);
            if (found != map.end()) {
                std::unordered_set<int> &exist = found->second;
                if (exist.find(neighbor->label) == exist.end()) out << "," << neighbor->label;
            }
            map[neighbor->label].emplace(node->label);
        }
        out << "#";
    } while (!cache.empty());
    std::string out_str = out.str();
    std::cout << out_str.substr(0, out_str.size()-1) << std::endl;
}

from leetcode.

Related Issues (19)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.