Golden programmer interview - interview questions 04.01 (traversing the drawing) via the inter-node

1. Topic

Inter-node path . Given directed to FIG, to design an algorithm to find out whether there is a path between two nodes.

示例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. Problem Solving

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;
    }
};
  • Adjacency list BFS
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;
    }
};

Here Insert Picture Description

  • DFS adjacency list
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;
    		}
    	}
    }
};

Here Insert Picture Description

Published 748 original articles · won praise 921 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104997925