Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Mandatory3;
- /*
- @author Lucas Gramme
- */
- import java.util.ArrayList;
- import java.util.Scanner;
- public class LetterLabyrinth2 {
- //Variables to save maze
- private int R, C;
- char[][] m;
- String[] input;
- //Starting point
- int sr = 0, sc = 0;
- //Track number of steps taken
- int move_count = 0;
- int node_left_in_layer = 1;
- int nodes_in_next_layer = 0;
- //Check if we have reached the end
- boolean reached_end = false;
- //Check if cell has been visited
- boolean visited[][] = new boolean[R][C];
- //North, south, east, west directions
- int[] dr = {-1, 1, 0, 0};
- int[] dc = {0, 0, 1, -1};
- //Queue
- ArrayList<Integer> rq = new ArrayList<>();
- ArrayList<Integer> cq = new ArrayList<>();
- public int solve(){
- rq.add(sr);
- cq.add(sc);
- visited[sr][sc] = true;
- while(rq.size() > 0){
- int r = rq.remove(0);
- int c = cq.remove(0);
- if(r == R-1 && c == C-1){
- move_count++;
- reached_end = true;
- break;
- }else{
- exploreNeighbours(r,c);
- node_left_in_layer--;
- if(node_left_in_layer == 0){
- node_left_in_layer = nodes_in_next_layer;
- nodes_in_next_layer = 0;
- move_count++;
- }
- }
- }
- if(reached_end){
- return move_count;
- }else {
- return -1;
- }
- }
- private void exploreNeighbours(int r, int c) {
- for(int i = 0; i < 4; i++){
- int rr = r + dr[i];
- int cc = c + dc[i];
- //Skip out of bounds locations
- if(rr < 0 || cc < 0)continue;
- if(rr >= R || cc >= C)continue;
- //Skip visited cells
- if(visited[rr][cc])continue;
- //Skip invalid cells
- if(m[rr][cc] == m[r][c])continue;
- //Add neighbour to queue
- rq.add(rr);
- cq.add(cc);
- //Set neighbour to visited = true and add to next layer
- visited[rr][cc] = true;
- nodes_in_next_layer++;
- }
- }
- public void run(){
- Scanner scan = new Scanner(System.in);
- //Maze will be RxC
- R = C = scan.nextInt();
- input = new String[R];
- m = new char[R][C];
- visited = new boolean[R][C];
- for(int i = 0; i < R; i++){
- input[i] = scan.next();
- for(int j = 0; j < R; j++){
- m[i][j] = input[i].charAt(j);
- }
- }
- System.out.println(solve());
- }
- public static void main(String[] args) {
- new LetterLabyrinth2().run();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement