图的深搜与广搜

Java实现图的遍历(深搜与广搜) 本文以邻接表作为存储结构,用Java实现图的遍历,话不多说,先给出的图的结构,如下: 深度优先搜索遍历 思想: 沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所有边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。(百 阅读详情

#include<iostream>
#include<queue>
#define MAXNUM 20
using namespace std;
struct Graph
{
    int Vertex[MAXNUM];
    int Arc[MAXNUM][MAXNUM];
    int VertexNum,ArcNum;
};

int n,m;
int vis[MAXNUM];
Graph G;
queue<int> q;
void dfs(int index)
{
    int i;
    cout<<index<<" ";
    vis[index]=1;
    for(i=0; i<G.VertexNum; i++)
        if(vis[i]==0&&G.Arc[index][i]!=0)
            dfs(i);
}
void dfsG()
{
    int i;
    for(i=0; i<G.VertexNum; i++)
        vis[i]=0;
    for(i=0; i<G.VertexNum; i++)
        if(vis[i]==0)
            dfs(i);
}

void bfs(int index)
{
    int i,num;
    cout<<index<<" ";
    vis[index]=1;
    q.push(index);

    while(!q.empty())
    {
        num=q.front();
        q.pop();
        for(i=0; i<G.VertexNum; i++)
        {
            if(G.Arc[num][i]!=0&&vis[i]==0){
                cout<<i<<" ";
                vis[i]=1;
                q.push(i);
            }
        }
    }
}
void bfsG()
{
    int i;
    for(i=0; i<G.VertexNum; i++)
        vis[i]=0;
    for(i=0; i<G.VertexNum; i++)
    {
        if(vis[i]==0)
        {
            bfs(i);
        }
    }
}


int main()
{
    cout<<"Put in Points and Arc?"<<endl;
    cin>>G.VertexNum>>G.ArcNum;
    cout<<"Put some information about arcs:For Example(0 1 power)"<<endl;
    for(int i=0; i<G.ArcNum; i++)
    {
        cin>>n>>m;
        cin>>G.Arc[n][m];//边权重
        //G.Arc[m][n]=G.Arc[n][m];//有向无向就差这一句话
    }
    cout<<"DFS:";
    dfsG();
    cout<<endl<<"---------"<<endl;
    cout<<"BFS:";
    bfsG();
    return 0;
}

首先图在计算机中的存储方式有两种。邻接矩阵和邻接表两种方式。但是就单纯的做题来说,邻接表方法太复杂。邻接矩阵相对简单。以下便是通过邻接矩阵来表示图,对图的dfs与bfs。由于自身学习时是需要带权重的。因此在后边增加了权重输入,根据要求可以更改。
linux离线安装nginx 阅读详情

相关推荐

【Qualcomm高通音频】如何封装音频控件?

音频代码涉及面很广,这篇文档介绍如何封装音频控件给HAL层使用。这里以AW87519芯片调试为例进行介绍封装音频控件和使用的方法。在最初接出到高通音频基础功能调试的时候,都是从tinyalsa指令/mixer_paths文件配置开始。因为单独一个音频设备的调试,都对应一条音频链路的打通。比如以下链接上高通平台基础音频输入输出设备调试: 【Qualcomm音频】Speaker 调试记录http...

crow_ch的博客 1955

Python实现图(Graph)及其算法(BFS)

注:参考书籍《Python数据结构与算法》 1.图的抽象数据类型定义 Graph()新建一个空图; addVertex(vert)向图中添加一个顶点(vert)实例; addEdge(fromVert,toVert)向图中添加一条有向边,用于连接顶点fromVert,toVert addEdge(fromVert,toVert,weight)向图中添加一条带权重(weight)的有向边 getVertex(vertKey)在图中找到名为vertKey的顶点 getVertices()以列表形

qq_42433311的博客 1万+

北斗B1频点信号捕获实战:如何应对NH码跳变带来的挑战?

本文深入探讨了北斗B1频点信号捕获中NH码跳变带来的核心挑战。针对NH码以1kHz速率调制导致的相干积分中断和相关峰畸变问题,文章提出并详细解析了一种基于伪码与多普勒频率分离技术的优化捕获方案。该方案通过差分处理消除NH跳变影响,并利用匹配滤波器与FFT分别进行码相位和多普勒频率的快速估计,有效提升了弱信号环境下的捕获灵敏度和稳定性,为北斗接收机设计提供了实用的工程参考。

joy55的博客 535

图的应用:词梯问题

1. 词梯问题 从一个单词演变到另一个单词,其中的过程可以经过多个中间单词。要求是相邻两个单词之间差异只能是1个字母,如FOOL变SAGE: FOOL>>POOL>>POLL>>POLE>>PALE>>SALE>>SAGE 我们的目标是找到最短的单词变换序列 采用图来解决这个问题的步骤如下: (1)将可能的单词之间的演变关系表达为图 (2)采用“广度优先搜索BFS”来搜寻从开始单词到结束单词之间的所有有效路径,选择其中最快到达目标单词的

weixin_38324954的博客 1755

SAP PI实战:5分钟搞定REST适配器同步接口配置(含Postman测试技巧)

本文详细介绍了如何在SAP PI中快速配置REST适配器同步接口,包括ESR设计、集成流配置及Postman测试技巧。通过实战步骤和关键参数设置,帮助开发者高效实现系统集成,特别适合需要实时数据交互的业务场景。

weixin_33738555的博客 485

机械革命重装Win11详细教程

通过以上步骤,你可以在机械革命电脑上成功重装Windows 11。虽然整个过程可能看起来有些复杂,但只要你按照步骤逐一进行,就能够顺利完成安装并享受到全新的操作系统带来的便利和性能提升。希望本文能够帮助到你,如果你有任何问题或疑问,请随时联系我们的技术支持团队。

mmoo_python的博客 3136

算法进阶之BFS 算法

BFS 算法 BFS 的核心思想应该不难理解的,就是把一些问题抽象成图,从一个点开始,向四周开始扩散。一般来说,我们写 BFS 算法都是用「队列」这种数据结构,每次将一个节点周围的所有节点加入队列。 BFS 相对 DFS 的最主要的区别是:BFS 找到的路径一定是最短的,但代价就是空间复杂度比 DFS 大很多. BFS 出现的常见场景就是让你在一幅「图」中找到从起点 start 到终点 target 的最近距离. 这个广义的描述可以有各种变体,比如走迷宫,有的格子是围墙不能走,从起点到终点的最短距离是多少?

AndyJ的学习之旅 1831

cJSON库用完后内存泄漏?手把手教你正确使用cJSON_Delete和free释放资源

本文深入解析cJSON库的内存管理机制,重点解决使用后的内存泄漏问题。通过详细讲解cJSON_Delete和free的正确使用方法,帮助开发者在处理JSON数据时有效释放资源,避免内存泄漏。特别适用于嵌入式系统和资源受限环境,提升开发效率和系统稳定性。

weixin_30808693的博客 419

PY数据结构-图

图是比树更为一般的结构,同样由节点和边构成。图中的基本组成部分为顶点Vertex,其具有名称标识key与数据项payload;两个顶点之间则通过边Edge来进行链接,便可以是有向/无向的,相应的图称之为有向图/无向图;为了表达从顶点到另一顶点的“代价”,则给边赋予了权重。图G可以定义为顶点与边的集合,即G=(V,E),而E中的每条边e=(v,w),v、w均为V中的顶点。若图G是赋权图,则边e中可以添加权重分量;图中的路径,则是由边连接起来的顶点序列。

m0_67703435的博客 837

智能车图像处理22-进阶篇14--小s的判断

这篇文章中主要讲述智能车图像处理中 : 小s的判断方法。

taiyuezyh的博客 2573

神州路由器DHCPv6配置

神州路由器DHCPv6配置.。

weixin_41687096的博客 462

图概念、创建以及遍历(DFS、BFS)——附完整代码

1 概念 1.1 定义 由顶点集V(Vertex)和边集E(Edge)组成,其中V为有限非空集合,E表示图中顶点之间的关系(边)集合。 1.2 相关概念 1 度:与该定点相连边的条数。对于有向图来说,顶点的出边条数为该顶点的出度,入边条数为该定点的入度。 2 创建 2.1 邻接矩阵 定义:对于二维数组G[N][N]两维分别表示图的顶点标号,即如果G[i][j]为1,说明顶点i和顶点j之间...

韩江雪de 小屋 1395

openwrt 固件定制详解:各类默认参数修改及应用添加

本文以friendlywrt22-rk3568发行版为例, 介绍如**何定制**一款**openwrt固件**,定制特性包括网络参数、登陆密码、开机界面(banner)、代理arp、opkg源、hostname、应用默认配置参数修改、增加任意文件(不限于应用程序及其库)等, 最后给出了一个完整的实操实例。

十年通信老兵的技术修炼之路——从3G到5G,从地面基站到卫星通信。 1546

树与图的深搜与广搜模板

树与图的深搜与广搜模板 一.图的存储 二.模板 深搜: 广搜: import java.util.*; public class Main{ static int[] h = new int[100010]; static int[] nodes = new int[100010]; static int[] next = new int[100010]; static boolean[] vis = new boolean[100010]; static int

qq_44932835的博客 272

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

图的遍历 - 邻接矩阵 - 深搜与广搜

深搜与广搜图论的遍历基础。而且今天讨论的是最简单的邻接矩阵。 下图是邻接矩阵的大致概念。 在C语言中邻接矩阵的定义方式如下://-----图的邻接矩阵存储表示----- #define MaxInt 32767//表示极大值 #define MVNum 100//最大顶点数 typedef char VerTexType;//假设顶点的数据类型为字符型 typedef int ArcType

Daioo 随笔 2373

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

图之深搜与广搜

无向带权图(邻接表)完成void BFS(Graph g,int k)函数,该函数从第k个点开始广度优先遍历图g,遍历过程中把访问过的顶点的visited设置为1(初始为0)。请注意,在测试代码中已经完成int locateVertex(Graph g, VertexType v);函数(在图g中查找顶点v的序号,不存在返回-1),你可以直接调用。我们这里怎么实现图的深搜:void DFS(Gra...

奇葩 1117

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

图的存储与深搜广搜

图 首先关于图的一些定义 箭头 <v,w>:意思是指箭头由v指向w,其中箭头是v,箭尾是w。如下图所示: 无向图: 两个点之间没有具体指向的图就是无向图。<v,w>==<w,v>。如下图所示: 有向图 两个点之间有具体的箭头指向。<v,w>不等于<w,v> 邻接表: 通常用邻接表来记录图上个节点之间的连接关系 如下图所示: 给每一个节点分别表上编号(0,1,2,3,4) 然后观察图可以知道节点A连接的节点有B,C,D所以A表中以A头节点的链

qq_45888103的博客 743

图的邻接表的创建与深搜/广搜

基于图的深度/广度优先搜索策略(邻接表的创建与深搜/广搜)#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;#include &lt;string.h&gt;using namespace std;typedef struct ArcNode{ int adjvex; //adjvex是整型,不是地址。也就是说邻接点域是元素 st...

碳酸钙的01妖精的博客 684

图的邻接矩阵存储与深搜广搜

存储结构   保存图的顶点名称,需要一个一维数组;保存顶点间的关系,需要一个二维数组;保存图的类型(有向图、无向图等)需要一个整形存储;另外,还需要明确图的顶点数与边数,方便创建等操作。 代码 #include<iostream> #include<cstring> #include<queue> #define INFINITY 0 using namespa...

cprimesplus的博客 381

图的dfs与bfs(深搜广搜)c++实现

#include #include #include #include #include using namespace std; int n; vector > graph; bool visited[100] = {0}; void dfs(int v) { list::iterator it; visited[v] = true; printf("%5d",

Edward_Wong的专栏 3315

图的基本操作与深搜广搜

最近在复习图论,主要是为了看一下深搜广搜算法。下面的例子中包含了基本的图的操作,以及深搜广搜算法,仅供记录。 #include <iostream> #include <string.h> #include <queue> using namespace std; #define MaxInt 32767 #define MvNum 100 bool visited[MvNum]={false}; //无向图 //图的数据结构 typedef struct { c

yageqin的博客 263

第三章 搜索与图论(一)——深搜,广搜,图的存储与拓扑序列

所有连通块包含两部分,一是以当前节点的子节点为根节点的连通块,以及删除当前节点与其子节点为根节点的连通块,剩下的部分也是一个连通块。若当前位置位于的行超过了矩阵的行,对矩阵的遍历结束,此时判断已经放置的皇后数量与题目要求的是否相等,若相等则输出棋盘。根据以上连通块的数量,维护一个最大值。即一个无向图,每个点的入度都不为0,那么从一个点开始,通过其入边能找到这条的起点,此时已经遍历了图中的2个点。枚举队头的所有出边,假设队头表示的点为t,删除队头的所有出边,假设出边的终点是u,即删除t->u。

凡事都是靠练习 1212

【Oped Judge 图】邻接表与邻接矩阵---实现深搜广搜

邻接表与邻接矩阵两种方式实现深度优先搜索和广度优先搜索

weixin_63444513的博客 268
下一篇: 关于几种排序的个人整理及分析
Linnnnnger
博客等级 码龄11年 71粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值