Created
August 19, 2018 14:03
-
-
Save rajatdiptabiswas/d8f7991ad129d4bafce9d20a9160889f to your computer and use it in GitHub Desktop.
Given a matrix, find the shortest distance from a source cell to a destination cell, traversing through limited cells only. Can move only up, down, left and right. If found output the distance else -1.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
class ShortestDistanceBetweenTwoCells { | |
static class Cell { | |
int row; | |
int col; | |
int distance; | |
Cell(int x, int y, int d) { | |
this.row = x; | |
this.col = y; | |
this.distance = d; | |
} | |
} | |
static Queue<Cell> queue = new LinkedList<>(); | |
static int shortestDistance(char[][] matrix) { | |
Cell source = new Cell(0,0,0); | |
int matrixRows = matrix.length; | |
int matrixCols = matrix[0].length; | |
boolean[][] visited = new boolean[matrixRows][matrixCols]; | |
for (int i = 0; i < matrixRows; i++) { | |
for (int j = 0; j < matrixCols; j++) { | |
if (matrix[i][j] == 'x') { | |
visited[i][j] = true; | |
} else if (matrix[i][j] == 's') { | |
source.row = i; | |
source.col = j; | |
} else { | |
visited[i][j] = false; | |
} | |
} | |
} | |
queue.add(source); | |
visited[source.row][source.col] = true; | |
while (!queue.isEmpty()) { | |
Cell item = queue.poll(); | |
if (matrix[item.row][item.col] == 'd') | |
return item.distance; | |
// move down | |
if (item.row+1 < matrixRows && !visited[item.row + 1][item.col]) { | |
queue.add(new Cell(item.row+1, item.col, item.distance+1)); | |
visited[item.row+1][item.col] = true; | |
} | |
// move up | |
if (item.row-1 >= 0 && !visited[item.row - 1][item.col]) { | |
queue.add(new Cell(item.row-1, item.col, item.distance+1)); | |
visited[item.row-1][item.col] = true; | |
} | |
// move right | |
if (item.col+1 < matrixCols && !visited[item.row][item.col+1]) { | |
queue.add(new Cell(item.row, item.col+1, item.distance+1)); | |
visited[item.row][item.col+1] = true; | |
} | |
// move left | |
if (item.col-1 >= 0 && !visited[item.row][item.col-1]) { | |
queue.add(new Cell(item.row, item.col-1, item.distance+1)); | |
visited[item.row][item.col-1] = true; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) { | |
/* | |
* s - source | |
* d - destination | |
* . - path | |
* x - wall | |
*/ | |
char[][] grid = { { 'x', 's', '.', '.' }, | |
{ 'x', 'x', '.', '.' }, | |
{ '.', '.', '.', 'x' }, | |
{ '.', 'x', 'x', 'x' }, | |
{ '.', '.', '.', 'd' } }; | |
System.out.println(shortestDistance(grid)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment