生活随笔
收集整理的這篇文章主要介紹了
图论算法(五)--求解割点、割边(JAVA)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
割點:對于一個連通圖來說,如果刪除某個點之后圖不再連通,這個點就稱為割點
割點算法
時間復(fù)雜度:O(N+M)
但是下面給出的算法時間復(fù)雜度為O(N^2),這是因為下面的存儲結(jié)構(gòu)都是鄰接矩陣,這樣的話用該算法就完全失去了意義,畢竟如果使用鄰接矩陣完全可以通過刪除一個點,然后進行DFS/BFS遍歷即可了。所以在實際應(yīng)用中還是要使用鄰接表來保存數(shù)據(jù),這樣時間復(fù)雜度可以達(dá)到O(N+M)
Input:
6 7
1 4
1 3
4 2
3 2
2 5
2 6
5 6
Output:
2
import java.util.Scanner;
public class cutPoint {
static int n, m;
static int[][] e =
new int[
9][
9];
static int[] num =
new int[
9];
static int[] low =
new int[
9];
static int[] flag =
new int[
9];
static int index,root;
static Scanner input =
new Scanner(System.
in);
public static void main(String[] args) {n = input.nextInt();m = input.nextInt();
for (
int i =
1; i <= n; i++) {
for (
int j =
1; j <= n; j++) {e[i][j] =
0;}}
for (
int i =
1; i <= m; i++) {
int x = input.nextInt();
int y = input.nextInt();e[x][y] =
1;e[y][x] =
1;}root =
1;dfs(
1, root);
for (
int i =
1; i <= n; i++) {
if (flag[i] ==
1) {System.
out.print(i +
" ");}}}
private static void dfs(
int cur,
int father) {
int child =
0;index++;num[cur] = index;low[cur] = index;
for (
int i =
1; i <= n; i++) {
if (e[cur][i] ==
1) {
if (num[i] ==
0) {child++;dfs(i, cur);low[cur] = Math.min(low[cur], low[i]);
if (cur != root && low[i] >= num[cur]) {flag[cur] =
1;}
if (cur == root && child ==
2) {flag[cur] =
1;}}
else if (i != father){low[cur] = Math.min(low[cur], num[i]);}}}}
}
割邊:對于一個連通圖來說,如果刪除某個邊之后圖不再連通,這個點就稱為割邊
割邊算法
時間復(fù)雜度:O(N+M)
同割點算法一樣,在實際應(yīng)用中還是要使用鄰接表來保存數(shù)據(jù),這樣時間復(fù)雜度可以達(dá)到O(N+M)
Input:
6 7
1 4
1 3
4 2
3 2
2 5
2 6
5 6
Output:
5-6
2-5
import java.util.Scanner;
public class cutEdge {
static int n, m;
static int[][] e =
new int[
9][
9];
static int[] num =
new int[
9];
static int[] low =
new int[
9];
static int index,root;
static Scanner input =
new Scanner(System.
in);
public static void main(String[] args) {n = input.nextInt();m = input.nextInt();
for (
int i =
1; i <= n; i++) {
for (
int j =
1; j <= n; j++) {e[i][j] =
0;}}
for (
int i =
1; i <= m; i++) {
int x = input.nextInt();
int y = input.nextInt();e[x][y] =
1;e[y][x] =
1;}root =
1;dfs(
1, root);}
private static void dfs(
int cur,
int father) {index++;num[cur] = index;low[cur] = index;
for (
int i =
1; i <= n; i++) {
if (e[cur][i] ==
1) {
if (num[i] ==
0) {dfs(i, cur);low[cur] = Math.min(low[i], low[cur]);
if (low[i] > num[cur]) {System.
out.println(cur +
"-" + i);}}
else if (i != father) {low[cur] = Math.min(low[cur], num[i]);}}}}
}
總結(jié)
以上是生活随笔為你收集整理的图论算法(五)--求解割点、割边(JAVA)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。