Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void Visit(int row, int col, int n, Queue<int> queue, bool[] visited)
- {
- if (row < 0 || col < 0 || row >= n || col >= n)
- return;
- int position = row * n + col;
- if (visited[position])
- return;
- visited[position] = true;
- queue.Enqueue(position);
- }
- public static int KnightHelper(int n, int i, int j)
- {
- if (i == j)
- {
- return ((n - 1) % i == 0) ? (n - 1) / i : -1;
- }
- //try bfs
- bool[] visited = new bool[n * n];
- Queue<int> queue = new Queue<int>();
- int steps = 0;
- queue.Enqueue(0);
- while (queue.Count > 0)
- {
- int count = queue.Count();
- for (int m = 0; m < count; m++)
- {
- int position = queue.Dequeue();
- int row = (position / n);
- int col = (position % n);
- if (row == n - 1 && col == n - 1)
- {
- // Found solution.
- return steps;
- }
- Visit(row + i, col + j, n, queue, visited);
- Visit(row + i, col - j, n, queue, visited);
- Visit(row + j, col + i, n, queue, visited);
- Visit(row + j, col - i, n, queue, visited);
- Visit(row - i, col + j, n, queue, visited);
- Visit(row - i, col - j, n, queue, visited);
- Visit(row - j, col + i, n, queue, visited);
- Visit(row - j, col - i, n, queue, visited);
- }
- steps++;
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement