ChaeYuriya

Untitled

Oct 28th, 2024
7
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Collections.Generic;
  4.  
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. int[,] maze = {
  10. { -1, 0, 1, 0, 3 },
  11. { 1, 0, 1, 0, 1 },
  12. { 0, 0, 0, 0, 1 },
  13. { 1, 1, 1, 0, 0 },
  14. { 1, 1, 0, 0, 1 }
  15. };
  16.  
  17. Stopwatch stopwatch = Stopwatch.StartNew();
  18. int shortestPath = FindShortestPath(maze);
  19. stopwatch.Stop();
  20.  
  21. if (shortestPath != -1)
  22. Console.WriteLine($"Jarak terpendek ke angka 3 adalah: {shortestPath} langkah.");
  23. else
  24. Console.WriteLine("Tidak ada jalur ke angka 3.");
  25.  
  26. Console.WriteLine($"Waktu eksekusi: {stopwatch.ElapsedMilliseconds} ms");
  27. }
  28.  
  29. static int FindShortestPath(int[,] maze)
  30. {
  31. int rows = maze.GetLength(0);
  32. int cols = maze.GetLength(1);
  33. (int x, int y) start = (-1, -1);
  34.  
  35. // Cari posisi awal (-1)
  36. for (int i = 0; i < rows; i++)
  37. {
  38. for (int j = 0; j < cols; j++)
  39. {
  40. if (maze[i, j] == -1)
  41. {
  42. start = (i, j);
  43. break;
  44. }
  45. }
  46. if (start.x != -1) break;
  47. }
  48.  
  49. if (start == (-1, -1))
  50. return -1; // Tidak ada posisi awal
  51.  
  52. // Queue untuk BFS
  53. Queue<(int x, int y, int distance)> queue = new Queue<(int, int, int)>();
  54. queue.Enqueue((start.x, start.y, 0));
  55.  
  56. // Array untuk mengatur arah gerakan (atas, bawah, kiri, kanan)
  57. int[] dx = { -1, 1, 0, 0 };
  58. int[] dy = { 0, 0, -1, 1 };
  59.  
  60. // Set untuk melacak posisi yang sudah dikunjungi
  61. bool[,] visited = new bool[rows, cols];
  62. visited[start.x, start.y] = true;
  63.  
  64. while (queue.Count > 0)
  65. {
  66. var (x, y, distance) = queue.Dequeue();
  67.  
  68. // Jika ditemukan angka 3
  69. if (maze[x, y] == 3)
  70. return distance;
  71.  
  72. // Mengecek empat arah
  73. for (int i = 0; i < 4; i++)
  74. {
  75. int nx = x + dx[i];
  76. int ny = y + dy[i];
  77.  
  78. if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && !visited[nx, ny] && maze[nx, ny] != 1)
  79. {
  80. visited[nx, ny] = true;
  81. queue.Enqueue((nx, ny, distance + 1));
  82. }
  83. }
  84. }
  85.  
  86. return -1; // Tidak ada jalur ke angka 3
  87. }
  88. }
  89.  
Add Comment
Please, Sign In to add comment