0% found this document useful (0 votes)
37 views2 pages

Code 1

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views2 pages

Code 1

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;

public class GridGame {


private static final int[][] DIRECTIONS = {
{1, 2},
{2, -1},
{-1, 1},
{-1, -2}
};

public static int minMoves(int[][] grid, int[] source, int[] destination, int[]
moveRule) {
int M = grid.length, N = grid[0].length;
boolean[][] visited = new boolean[M][N];
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{source[0], source[1], 0});
visited[source[0]][source[1]] = true;

while (!queue.isEmpty()) {
int[] current = queue.poll();
int x = current[0], y = current[1], steps = current[2];

if (x == destination[0] && y == destination[1]) {


return steps;
}

for (int[] direction : DIRECTIONS) {


int newX = x + moveRule[0] * direction[0];
int newY = y + moveRule[1] * direction[1];

if (isValid(newX, newY, M, N, grid, visited)) {


visited[newX][newY] = true;
queue.add(new int[]{newX, newY, steps + 1});
}
}
}
return -1;
}

private static boolean isValid(int x, int y, int M, int N, int[][] grid,


boolean[][] visited) {
return x >= 0 && x < M && y >= 0 && y < N && grid[x][y] == 0 && !visited[x]
[y];
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("Enter grid dimensions M and N:");


int M = sc.nextInt();
int N = sc.nextInt();

System.out.println("Enter grid (0 for open cells, 1 for blocked cells):");


int[][] grid = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
grid[i][j] = sc.nextInt();
}
}
int[] source = new int[]{sc.nextInt(), sc.nextInt()};

int[] destination = new int[]{sc.nextInt(), sc.nextInt()};

int[] moveRule = new int[]{sc.nextInt(), sc.nextInt()};

int result = minMoves(grid, source, destination, moveRule);


System.out.println(result);
}
}

You might also like