Advertisement
Guest User

Untitled

a guest
Aug 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. public static void Visit(int row, int col, int n, Queue<int> queue, bool[] visited)
  2. {
  3. if (row < 0 || col < 0 || row >= n || col >= n)
  4. return;
  5. int position = row * n + col;
  6. if (visited[position])
  7. return;
  8. visited[position] = true;
  9. queue.Enqueue(position);
  10. }
  11. public static int KnightHelper(int n, int i, int j)
  12. {
  13. if (i == j)
  14. {
  15. return ((n - 1) % i == 0) ? (n - 1) / i : -1;
  16. }
  17.  
  18. //try bfs
  19. bool[] visited = new bool[n * n];
  20. Queue<int> queue = new Queue<int>();
  21. int steps = 0;
  22. queue.Enqueue(0);
  23. while (queue.Count > 0)
  24. {
  25. int count = queue.Count();
  26. for (int m = 0; m < count; m++)
  27. {
  28. int position = queue.Dequeue();
  29. int row = (position / n);
  30. int col = (position % n);
  31.  
  32. if (row == n - 1 && col == n - 1)
  33. {
  34. // Found solution.
  35. return steps;
  36. }
  37.  
  38. Visit(row + i, col + j, n, queue, visited);
  39. Visit(row + i, col - j, n, queue, visited);
  40. Visit(row + j, col + i, n, queue, visited);
  41. Visit(row + j, col - i, n, queue, visited);
  42. Visit(row - i, col + j, n, queue, visited);
  43. Visit(row - i, col - j, n, queue, visited);
  44. Visit(row - j, col + i, n, queue, visited);
  45. Visit(row - j, col - i, n, queue, visited);
  46. }
  47. steps++;
  48. }
  49. return -1;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement