拓扑 java_拓扑排序 JAVA - osc_7wxos2yx的个人空间 - OSCHINA - 中文开源技术交流社区...

判断是否成环 JAVA 代码实现

import java.util.LinkedList;

import java.util.Scanner;

public class Hello{

static int[][]mp;

static int[] indegree;

static int N, M;

static LinkedList list = new LinkedList();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

N = sc.nextInt();

M = sc.nextInt();

mp = new int[N][N];

indegree = new int[N];

for(int i = 0; i < N; i ++) {

indegree[i] = 0;

for(int j = 0; j < N; j ++) {

mp[i][j] = 0;

}

}

int x, y;

for(int i = 0; i < M; i ++) {

x = sc.nextInt();

y = sc.nextInt();

if(mp[x][y] == 0) {

mp[x][y] = 1;

indegree[y] ++;

}

}

topSort();

}

private static void topSort() {

int cnt = 0;

for(int i = 0; i < N; i ++) {

if(indegree[i] == 0) {

list.addFirst(i);

indegree[i] = -1;

}

}

while(!list.isEmpty()) {

int p = list.removeFirst();

System.out.print(p + " ");

cnt ++;

for(int j = 0; j < N; j ++) {

if(mp[p][j] == 1) {

mp[p][j] = 0;

indegree[j] --;

if(indegree[j] == 0) {

list.addFirst(j);

indegree[j] = -1;

}

}

}

}

System.out.println();

if(cnt < N) System.out.println("Cycleeeeee!");

else System.out.println("Nooooooooo!");

}

}

但是上述是建立邻接矩阵的写法 当 N 太大的时候就不是很好了 所以可以用链表来存边和边的关系 会节省内存 所以以下是链表存图并判断拓扑关系

import java.util.concurrent.ArrayBlockingQueue;

import java.util.LinkedList;

import java.util.Queue;

import java.util.Scanner;

public class Hello{

static int N, M;

static int[] v;

static int[] nx;

static int[] h;

static int[] ans;

static int[] in;

static int cnt, sz;

static LinkedList list = new LinkedList();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

v = new int[100010];

nx = new int[100010];

h = new int[100010];

in = new int[100010];

N = sc.nextInt();

M = sc.nextInt();

init();

for(int i = 0; i < M; i ++) {

int x, y;

x = sc.nextInt();

y = sc.nextInt();

add(x, y);

}

topSort();

}

public static void init() {

for(int i = 0; i < 100010; i ++) {

h[i] = -1;

in[i] = 0;

}

sz = 0;

}

public static void add(int a, int b) {

v[sz] = b;

nx[sz] = h[a];

h[a] = sz;

in[b] ++;

sz ++;

}

public static void topSort() {

for(int i = 0; i < N; i ++) {

if(in[i] == 0) list.addFirst(i);

}

while(!list.isEmpty()) {

int tp = list.removeFirst();

System.out.print(tp + " ");

cnt ++;

for(int i = h[tp]; i != -1; i = nx[i]) {

in[v[i]] --;

if(in[v[i]] == 0) list.addFirst(v[i]);

}

}

System.out.println();

if(cnt != N)

System.out.println("Circleeeeeeeeee");

else System.out.println("Noooooooooo");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值