01/10/2018, 12:01

Hỏi về bài hasDeadlock trong phần graph trên Codefight Interview

Đề như vầy còn đây là bài giải của em. Em chạy được test 1 và 2, còn mấy test khác thì ouput: empty. Có chạy mấy test đó trên codeblocks + vs2017 thì đều chạy ra đúng kết quả, không hiểu sao đem lên web thì ra empty. Có bác nào chỉ giúp em chỗ sai, nếu không thì cho em xin solution cũng được ạ. Tìm trên gg cũng ko ra solution bài này. Em cảm ơn.

bool solve(vector<vector<int>> connections,int currentNode,int startNode, vector<int> path) {
 if (currentNode== startNode&&path.size()>1) {
	return true;
}
else {
	for (int j = 0; j < connections[currentNode].size(); j++) {	
		path.push_back(connections[currentNode][j]);
		if (solve(connections, connections[currentNode][j], startNode, path)) {
			return true;
		}
		path.pop_back();
	}
}
return false;
}

bool hasDeadlock(vector<vector<int>>  connections) {
vector<int> path;
for (int i = 0; i < connections.size(); i++){
	path.push_back(i);
	if (solve(connections, i, i, path))
		return true;
	path.pop_back();
}
return false;
}
HK boy viết 14:11 ngày 01/10/2018
  • Có vẻ như bạn đang muốn code DFS? Mình thấy code của bạn hao hao DFS, mà trông cũng hơi dị và phức tạp.
  • Đề có đúng là kiểm tra xem có tồn tại 1 circle trong graph này không thế?
levana viết 14:05 ngày 01/10/2018

thuật toán của em là: duyệt tất cả đỉnh rồi từ đỉnh đó duyệt DFS như bác nói nếu duyệt mà tới lại điểm ban đầu thì return true, không thì false. Mà nó chỉ cần 1 vòng thôi (ví dụ có 5 đỉnh chỉ cần tồn tại 1 2 3 1 là đc rồi) ko cần phải như hamilton. Vậy thôi ạ. Em thử các test trong web đưa ra ở ide thì đúng cả nhưng khi lên web thì ra empty. Bác có solution thì quăng em, em submit qua bài mới cũng đc. Cảm ơn

Gió viết 14:03 ngày 01/10/2018

Thuật toán có vẻ không sai, nhưng hàm solve không có biến nào tên là path cả.

levana viết 14:07 ngày 01/10/2018

À sorry bác, ban đầu em để hamilton, mà do nó ko phải là hamilton nên em đổi thành path rồi mới up lên đây ^^ sr sr. Mà cái đó ko ảnh hưởng gì đâu bác. Nó vẫn sai từ test 3 trở đi

HK boy viết 14:15 ngày 01/10/2018

Thuật toán thì đơn giản nhưng mà code phức tạp quá. Suy nghĩ “chân phương” thôi:

void dfs(u):
    count_next = 0
    for v in G[u]:
        if (!visited[u]):
            count_next++
            dfs(v)

    if count_next == 0:
        // Có đáp số
Hung viết 14:12 ngày 01/10/2018

Thuật toán Tarjan

en.m.wikipedia.org

Tarjan's strongly connected components algorithm

Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. Tarjan's algorithm is named for its inventor, Robert Tarjan. The algorithm takes a directed graph as input, and produces a partition of the graph's vertices into the graph's strongly connected components. Each vertex of the graph appears in...

Bài liên quan
0