fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Graphdfs
  6. {
  7. private int[][] matrix; // Матрица смежности будет записана именно сюда.
  8. private int n; // Число вершин.
  9. private int[] was;// Массив цвета вершины.
  10. public Graphdfs(){}
  11. public Graphdfs(int n)
  12. {
  13. this.n = n;
  14. matrix = new int [n][n];
  15. was = new int [n];
  16. }
  17. public void setMatrix(Scanner in)
  18. {
  19. for(int i = 0; i < n; i++)
  20. for(int j = 0; j < n; j++)
  21. matrix[i][j] = in.nextInt();
  22. }
  23. public void showMatrix()
  24. {
  25. for(int i = 0; i < n; i++)
  26. {
  27. for(int j = 0; j < n; j++)
  28. {
  29. System.out.print(matrix[i][j]);
  30. if(j < n - 1) System.out.print(" ");
  31. else System.out.println();
  32. }
  33. }
  34. }
  35. public boolean dfs(int key)
  36. {
  37. was[key] = 1;
  38. for(int i = 0; i < n; i++)
  39. {
  40. if(matrix[key][i] != 0)
  41. {
  42. if(was[i] == 0){
  43. if(dfs(i)) return true;
  44. }
  45. else if(was[i] == 1){
  46. return true;
  47. }
  48. }
  49. }
  50. was[key] = 2;
  51. return false;
  52. }
  53. public int[] getWas(){
  54. return was;
  55. }
  56. }
  57.  
  58. public class Main
  59. {
  60. public static void main (String[] args) throws java.lang.Exception
  61. {
  62. System.out.println("ok1");
  63. Scanner in = new Scanner(System.in);
  64. System.out.println("ok2");
  65. int n = in.nextInt();
  66. System.out.println("ok3");
  67. Graphdfs Graph = new Graphdfs(n);
  68. System.out.println("ok4");
  69. Graph.setMatrix(in);
  70. System.out.println("ok5");
  71. Graph.showMatrix();
  72. for(int i = 0; i < n; i++){
  73. if(Graph.getWas()[i] == 0 &&Graph.dfs(i) == true) {System.out.println(1); System.exit(0);}
  74. }
  75. System.out.println(0);
  76. }
  77. }
Success #stdin #stdout 0.14s 321280KB
stdin
3
0 1 0
0 0 1
0 0 0
stdout
ok1
ok2
ok3
ok4
ok5
0 1 0
0 0 1
0 0 0
0