任务管理系统算法-Kahn’s algorithm for Topological Sorting(一)

本文介绍如何利用Kahn’s algorithm进行任务管理系统的拓扑排序。通过设计Graph类存储任务依赖关系,实现任务的入度计算,并使用队列进行任务排序。在循环中不断取出入度为0的任务,直到所有无环任务完成。若有未完成任务,则表示存在依赖环。
摘要由CSDN通过智能技术生成

上一遍分析了如何设计任务管理系统的算法,拓扑排序之任务管理系统思路设计

今天我们就利用Kahn’s algorithm for Topological Sorting来实现任务管理系统算法。

设计一个数据结构Graph类来储存各个task之间的依赖关系,并根据每个task相互的依赖关系找出任务排列顺序。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Graph {
	private int V;    // No. of vertices
	private int minimumLevel;
	private int tasksInLevel;    // store the number of tasks in the same level
	private List<ArrayList<Integer>> adj;
	private List<String> tasks;
	private boolean isUnique = true;
	private boolean isCircle = false;
	private Queue<Integer> mCircleQueue = new LinkedList<Integer>();   // store the circle tasks in order
	private boolean isFound = false;    // If we find circle, then isFound is true
	
	public Graph() {
		this.V = 0;
		adj = new ArrayList<ArrayList<Integer>>();
		tasks = new ArrayList<String>();
	}
	
	public Graph(String loadTasks[]) {
		this.V = loadTasks.length;
		adj = new ArrayList<ArrayList<Integer>>();
		for(int i = 0; i < V; i++) {
			adj.add(new ArrayList<Integer>());
		}
		tasks = new ArrayList<String>();
		for(String task : loadTasks) {
			tasks.add(task);
		}
	}
	
	public void addTask(String s) {
		if(!tasks.contains(s)) {
			adj.add(new ArrayList<Integer>());
			this.V++;
			tasks.add(s);
		} else {
			System.out.println("Task " + s + " is already in the system, please add another task or quit.");
		}
	}
	
	// Add dependency for last added task
	public void addDependency(String s) {
		if(!tasks.contains(s)) {
			System.out.println("Task " + s + " is not in the system, pl
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值