Advertisement
Guest User

Untitled

a guest
Feb 6th, 2014
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import org.openjdk.jmh.annotations.*;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Queue;
  5. import java.util.Random;
  6. import java.util.concurrent.TimeUnit;
  7.  
  8. @State(Scope.Benchmark)
  9. @Fork(1)
  10. @BenchmarkMode(Mode.AverageTime)
  11. @OutputTimeUnit(TimeUnit.NANOSECONDS)
  12. public class Graph {
  13.     private int[][] g;
  14.     private static final int SIZE = 1000;
  15.  
  16.     @Setup
  17.     public void setup() {
  18.         Random r = new Random();
  19.         g = new int[SIZE][SIZE];
  20.  
  21.         for (int i = 0; i < SIZE; i++) {
  22.             for (int j = 0; j < SIZE; j++) {
  23.                 if (i == j) continue;
  24.                 if (r.nextBoolean()) {
  25.                     g[i][j] = g[j][i] = 1;
  26.                 }
  27.             }
  28.         }
  29.  
  30.     }
  31.  
  32.     private class DfsRunner {
  33.         boolean[] visited;
  34.  
  35.         public DfsRunner() {
  36.             visited = new boolean[SIZE];
  37.         }
  38.  
  39.         public void run(int v) {
  40.             visited[v] = true;
  41.             for (int u = 0; u < SIZE; u++) {
  42.                 if (g[v][u] == 1 && !visited[u]) {
  43.                     run(u);
  44.                 }
  45.             }
  46.         }
  47.     }
  48.  
  49.     @GenerateMicroBenchmark
  50.     public boolean dfs() {
  51.         DfsRunner dfsRunner = new DfsRunner();
  52.         dfsRunner.run(0);
  53.         for (int i = 0; i < SIZE; i++) {
  54.             if (!dfsRunner.visited[i]) return false;
  55.         }
  56.         return true;
  57.     }
  58.  
  59.     @GenerateMicroBenchmark
  60.     public boolean bfs() {
  61.         boolean[] visited = new boolean[SIZE];
  62.  
  63.         Queue<Integer> queue = new ArrayDeque<>();
  64.         queue.add(0);
  65.  
  66.         while (!queue.isEmpty()) {
  67.             int v = queue.poll();
  68.             visited[v] = true;
  69.             for (int u = 0; u < SIZE; u++) {
  70.                 if (g[v][u] == 1 && !visited[u]) {
  71.                     visited[u] = true;
  72.                     queue.add(u);
  73.                 }
  74.             }
  75.         }
  76.  
  77.         for (int i = 0; i < SIZE; i++) {
  78.             if (!visited[i]) return false;
  79.         }
  80.         return true;
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement