You are viewing a single comment's thread. Return to all comments →
"Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell". remember that
import java.util.*; public class Solution { static int[] xMove = {-1, 0, 1, 0 }; static int[] yMove = { 0, 1, 0, -1}; public static boolean isSafe (int n, int x, int y, char[][] matrix) { return (x >= 0 && y >= 0 && x < n && y < n && matrix[x][y] == '.'); } public static int solve(int n, char[][] matrix, int startX, int startY, int goalX, int goalY) { LinkedList<Integer> queueX = new LinkedList<>(); LinkedList<Integer> queueY = new LinkedList<>(); int[][] step = new int[n+1][n+1]; boolean[][] visited = new boolean[n+1][n+1]; queueX.add(startX); queueY.add(startY); visited[startX][startY] = true; while (!queueX.isEmpty()) { int curX = queueX.poll(); int curY = queueY.poll(); for (int i = 0; i < 4; i++) { int index = 1; while (isSafe(n, curX+xMove[i]*index, curY + yMove[i]*index, matrix) && !visited[curX+xMove[i]*index][curY + yMove[i]*index]) { int nextX = curX + xMove[i]*index; int nextY = curY + yMove[i]*index; visited[nextX][nextY] = true; queueX.add(nextX); queueY.add(nextY); step[nextX][nextY] = step[curX][curY] +1; if (nextX == goalX && nextY == goalY) { return step[nextX][nextY]; } index++; } } } return -1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); char[][] matrix = new char[n+1][n+1]; scanner.nextLine(); for (int i = 0; i < n; i++) { String line = scanner.nextLine(); for (int j = 0; j < n; j++) { matrix[i][j] = line.charAt(j); } } int startX = scanner.nextInt(); int startY = scanner.nextInt(); int goalX = scanner.nextInt(); int goalY = scanner.nextInt(); int result = solve(n, matrix, startX, startY, goalX, goalY); System.out.println(result); scanner.close(); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Castle on the Grid
You are viewing a single comment's thread. Return to all comments →
"Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell". remember that