程序员面试金典 - 面试题 04.01. 节点间通路(图的遍历)

2020-07-13 16:45:23 浏览数 (1)

1. 题目

节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。

代码语言:javascript复制
示例1:
 输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]],
 start = 0, target = 2
 输出:true
示例2:
 输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], 
 start = 0, target = 4
 输出 true
 
提示:
节点数量n在[0, 1e5]范围内。
节点编号大于等于 0 小于 n。
图中可能存在自环和平行边。

2. 解题

  • 邻接矩阵 内存超限
代码语言:javascript复制
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
    	bool visited[n] = {false};
    	visited[start] = true;
    	queue<int> q;
    	int tp, i;
    	q.push(start);
    	vector<vector<int>> map(n,vector<int>(n,0));
    	for(i = 0; i < graph.size();   i)
    		map[graph[i][0]][graph[i][1]] = 1;
    	while(!q.empty())
    	{
    		tp = q.front();
    		q.pop();
    		if(tp == target)
    			return true;
    		for(i = 0; i < n;   i)
    		{
    			if(!visited[i] && map[tp][i]==1)
    			{
    				visited[i] = true;
    				q.push(i);
    			}
    		}
    	}
    	return false;
    }
};
  • 邻接表 BFS
代码语言:javascript复制
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
    	bool visited[n] = {false};
    	visited[start] = true;
    	vector<vector<int>> map(n);
    	int i, tp;
    	for(i = 0; i < graph.size();   i)
    	{
    		map[graph[i][0]].push_back(graph[i][1]);
    	}
    	queue<int> q;
    	q.push(start);
    	while(!q.empty())
    	{
    		tp = q.front();
    		if(tp == target)
    			return true;
    		q.pop();
    		for(i = 0; i < map[tp].size();   i)
    		{
    			if(!visited[map[tp][i]])
    			{
    				q.push(map[tp][i]);
    				visited[map[tp][i]] = true;
    			}
    		}
    	}
    	return false;
    }
};
  • 邻接表 DFS
代码语言:javascript复制
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
    	bool visited[n] = {false};
    	visited[start] = true;
    	vector<vector<int>> map(n);
    	for(int i = 0; i < graph.size();   i)
    	{
    		map[graph[i][0]].push_back(graph[i][1]);
    	}
    	bool found = false;
    	dfs(map,start,target,found,visited);
    	return found;
    }

    void dfs(vector<vector<int>>& map , int start, int& target, bool& found, bool* visited)
    {
    	if(start == target)
    		found = true;
    	if(found)
    		return;
    	for(int i = 0; i < map[start].size();   i)
    	{
    		if(!visited[map[start][i]])
    		{
    			visited[map[start][i]] = true;
    			dfs(map,map[start][i],target,found,visited);
    			visited[map[start][i]] = false;
    		}
    	}
    }
};

0 人点赞