数据结构——图的算法练习题

数据结构——图算法题总结(持续更新)

DFS

对于DFS的理解

DFS是从某个结点出发,首先找到一个相邻的结点,遍历到底,直到第一个结点完全遍历完毕之后,才会开始从第二个相邻的结点出发继续之前的操作,对于一个图
一张图
其深度优先遍历的过程为
在这里插入图片描述

  1. 判断从结点u到v是否又简单路径

题目描述:对于无向图给定一个图的邻接表或者邻接矩阵,设计一个算法,判断从结点u到结点v是否存在简单路径

简单路径指的是,从顶点u到顶点v的这一条路径上,不存在重复的顶点,对于这个,从顶点u开始进行深度优先遍历,在深度优先遍历的过程中,如果遇到了顶点v,则返回True,如果深度优先遍历完毕之后还没有找到顶点v,那么返回False,即没有从u到v的简单路径

c++实现

bool existPath(vector<vector<int>> &matrix,int startNode,int aimNode){
    //判断传入的参数是否正确
    if(matrix.size() != matrix[0].size())
        throw runtime_error("matrix is incorrect");
    if(startNode>matrix.size() || aimNode>matrix.size())
        throw runtime_error("index out of range");
    if(startNode == aimNode)
        return true;
    //前期准备
    int i = startNode - 1,j,len = matrix.size();
    vector<bool> flag(len,false);
    vector<int> stack;
    flag[i] = true;
    stack.push_back(i);
    //开始深度递归
    while(!stack.empty()){
        i = stack.back();
        stack.pop_back();
        if(i+1 == aimNode)
            return true;
        for(j=0;j<len;j++){
            if(matrix[i][j] != 0 && !flag[j]){
                flag[j] = true;
                stack.push_back(j);
            }
        }
    }
    return false;
}

python实现

使用的是python3

def existPath(matrix:tuple,startNode:int,aimNode:int)->bool:
	"""
	tuple是邻接矩阵
	startNode是起始结点
	aimNode是目标结点
	"""
	if startNode == aimNode:
		return True
	# 前期准备
	i = startNode-1;lens = len(matrix)
	stack = list()
	flag = [False]*lens  # 构建一个重复lens次,值为False的列表
	stack.append(i)
	flag[i] = True
	# 开始深度递归
	while len(stack) != 0:
		i = stack[-1]
		del stack[-1]
		if i+1 == aimNode:
			return True
		for j in range(len(matrix)):
			if matrix[i][j] != 0 and not flag[j]:
				flag[j] = True
				stack.append(j)
	return False

java实现

    boolean existPath(int[][] matrix,int startNode,int aimNode){
        //验证传入的参数是否正确
        if(matrix.length!=matrix[0].length)
            throw new RuntimeException("matrix length is incorrect");
        if(startNode>matrix.length || aimNode>matrix.length)
            throw new IndexOutOfBoundsException("Index out of range");
        if(startNode == aimNode)
            return true;
        //前期准备
        int i = startNode-1;  //创建临时变量
        int j,len = matrix.length;
        int [][] temp_matrix = matrix;
        boolean[] flag = new boolean[len];
        for(j=0;j<len;++j){
            flag[j] = false;
        }
        flag[i] = true;  //使用栈来实现递归的过程
        Stack<Integer> stack = new Stack<>();
        stack.push(i);
        //开始深度优先遍历
        while(!stack.empty()){
            i = stack.pop();
            if(i+1 == aimNode)
                return true;
            for(j=0;j<len;++j){
                if(temp_matrix[i][j]!=0 && !flag[j]){
                    flag[j] = true;
                    stack.push(j);
                }
            }
        }
        return false;
    }

BFS

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
算法sicily例题 1000. sicily 1155. Can I Post the lette Time Limit: 1sec Memory Limit:32MB Description I am a traveler. I want to post a letter to Merlin. But because there are so many roads I can walk through, and maybe I can’t go to Merlin’s house following these roads, I must judge whether I can post the letter to Merlin before starting my travel. Suppose the cities are numbered from 0 to N-1, I am at city 0, and Merlin is at city N-1. And there are M roads I can walk through, each of which connects two cities. Please note that each road is direct, i.e. a road from A to B does not indicate a road from B to A. Please help me to find out whether I could go to Merlin’s house or not. Input There are multiple input cases. For one case, first are two lines of two integers N and M, (N<=200, M<=N*N/2), that means the number of citys and the number of roads. And Merlin stands at city N-1. After that, there are M lines. Each line contains two integers i and j, what means that there is a road from city i to city j. The input is terminated by N=0. Output For each test case, if I can post the letter print “I can post the letter” in one line, otherwise print “I can't post the letter”. Sample Input 3 2 0 1 1 2 3 1 0 1 0 Sample Output I can post the letter I can't post the letter Source Code #include <iostream> #include <vector> using namespace std; int n,m; vector<int> vout[200]; bool visited[200]; bool flood(int u) { visited[u]=1; if (u==n-1) return 1; for (int x=0; x<vout[u].size(); x++) { int &v=vout[u][x]; if (!visited[v] && flood(v)) return 1; } return 0; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值