This question was asked in interview. Given grid 4X4, you are give some arbitrary point suppose point (2,2)(index starting from 0), from there you want to start, print one any path from there you can exit grid. You are allow to move LEFT, RIGHT, TOP, BOTTON. In following grid, 1 - represents block, 0 : you can move.
1 0 1 1
0 0 0 0
1 1 0 1
1 1 1 1
Exit path for above grid is, (2, 2)=> (1, 2) => (1, 1) => (0, 1)
I tried to solve this problem (below), through DFS, but I am not able find the solution how to print any one of Path, Following is printing all Path, I just want to print any Path.
public boolean isValidMove(Point point){
if(array[point.getX()][point.getY()]==0){
return true;
}
return false;
}
public void printTraversal(int [][] array, int M, int N, Point start){
boolean [] visited = boolean[M*N];
Arrays.fill(visited, false);
int index = start.getX()*M+ start.getY();
boolean[index] = true;
Stack<Point> stack = new Stack<Point>();
stack.push(start);
while(!stack.isEmpty()){
Point point = stack.pop();
System.out.println(point.getX()+", "+ point.getY());
int x = point.getX();
int y = point.getY();
if(isValidMove(x-1, y-1)){
stack.push(new Point(x-1, y-1));
}
if(isValidMove(x-1, y)){
stack.push(new Point(x-1, y));
}
if(isValidMove(x, y-1)){
stack.push(new Point(x, y-1));
}
if(isValidMove(x+1, y+1)){
stack.push(new Point(x+1, y+1));
}
}
}
class Point{
private int X;
private int Y;
public Point(int X, int Y){
this.X = X;
this.Y = Y;
}
public int getX(){
return this.X;
}
public int getY(){
return this.Y;
}
}
You need another utility function to check if current point is about to exit or not.
public boolean isExit(Point point, int M, int N) {
int x = Point.getX();
int y = point.getY();
return (x == 0 || y == 0 || x == M - 1 || y == N - 1);
}
And now in while loop, when you encounter a exit point, print and exit the loop. Also you need to correct the isValidMove and printTraversal function a bit.
public boolean isValidMove(Point point, int M, int N) {
int x = Point.getX();
int y = point.getY();
if(x >= 0 && y >= 0 && x < M && y < N && array[x][y] == 0 ) {
return true;
}
return false;
}
private int getIndx(Point p, int M) {
return p.getX() * M + p.getY();
}
public void printTraversal(int [][] array, int M, int N, Point start){
if(M == 0 || N == 0) {
return;
}
boolean [] visited = boolean[M * N];
Arrays.fill(visited, false);
visited[ getIndx(start, M) ] = true;
Stack<Point> stack = new Stack<Point>();
stack.push(start);
while(!stack.isEmpty()) {
Point point = stack.pop();
System.out.println(point.getX()+", "+ point.getY());
if(isExit(point, M, N))
break;
int x = point.getX();
int y = point.getY();
Point neigh = new Point(x-1, y-1);
if(isValidMove(x-1, y-1, M, N) && !visited[ getIndx(neigh, M) ]){
stack.push( neigh );
visited[ getIndx(neigh, M) ] = true;
}
// For other 3 sides
// .............
}
}
Related
Give a list of mines, each mine contains 3 numbers, x, y coordinates and explosion range . Find the initial mine that can eventually detonate the most mines and maximum number of mine it denotes.
the x, y coordinates can be negative numbers and all three numbers can be double.
I coded a dfs solution but got incorrect result. Does it seem like an ok implementation . Any inputs will be helpful.
List<Node> list;
RadiusBlast(List<Node> list){
this.list = list;
}
static boolean isInside(int circle_x, int circle_y,
int rad, int x, int y)
{
// Compare radius of circle with
// distance of its center from
// given point
//System.out.println("source:"+ circle_x + "," + circle_y);
if ((x - circle_x) * (x - circle_x) +
(y - circle_y) * (y - circle_y) <= rad * rad) {
//System.out.println("isInside:"+ x + "," + y);
return true;
}
else
return false;
}
public int dfs2(int i,Node node,boolean[] visited) {
//System.out.println("dfs");
visited[i] = true;
int res = 1;
for(Node newNode : list){
if(!visited[newNode.index]) {
if (isInside(node.x, node.y, node.r, newNode.x, newNode.y))
res += dfs2(newNode.index,node,visited);
}
}
return res;
}
static class Node{
int x,y,r ;
int index;
boolean depthvisited;
//boolean visited;
public Node(int x, int y, int r,int index) {
this.x = x;
this.y = y;
this.r = r;
this.index = index;
}
}
// Driver Program to test above function
public static void main(String arg[])
{
//RadiusBlast r = new RadiusBlast();
int x = -1, y = 3;
x = 2 ; y = 3;
int x1 = 2 ; int y2 = 3 ;
int circle_x = 0, circle_y = 7, rad = 5;
if (isInside(circle_x, circle_y, rad, x, y))
System.out.println("Inside1 main");
else
System.out.println("Outside");
if (isInside(circle_x, circle_y, rad, x1, y2))
System.out.println("Inside2 main");
else
System.out.println("Outside ");
//x1, y1, r1
// 2,3,3
// -1,3,2
// 3,2,5
List<Node> list = new ArrayList<Node>();
list.add(new Node(2,3,3,0));
list.add(new Node(2,3,1,1));
list.add(new Node(0,7,5,2));
boolean[] visited;
RadiusBlast r = new RadiusBlast(list);
int res =0 ;
for(int i =0; i < list.size(); i++){
visited = new boolean[list.size()];
res = Math.max(res,r.dfs2(list.get(i).index,list.get(i),visited));
//System.out.println("res:" + (res));
}
System.out.println("result:" + (res - 1));
}
Iterate over mines list and explode each mine recursively. Collect exploded count and pick maximum one. Something like this:
public class Test {
public static void main(String[] args) throws Exception {
List<Node> list = new ArrayList<Node>();
list.add(new Node(2, 3, 3, 0));
list.add(new Node(2, 3, 1, 1));
list.add(new Node(0, 7, 5, 2));
System.out.println("Deadliest node is: " + findDeadliest(list).index);
}
public static Node findDeadliest(List<Node> mines) {
Node result = mines.get(0);
for(Node n : mines) {
List<Node> exploded = new ArrayList<>();
explode(n, mines, exploded);
n.triggeredCount = exploded.size();
result = (n.triggeredCount > result.triggeredCount) ? n : result;
}
return result;
}
public static void explode(Node mine, List<Node> mines, List<Node> exploded){
for(Node target: mines) {
if(!exploded.contains(target)) {
if(isInside(mine, target)) {
exploded.add(target);
explode(target, mines, exploded);
}
}
}
}
static boolean isInside(Node s, Node t) {
double d = Math.pow(s.r,2) - ( Math.pow(s.x-t.x, 2) + Math.pow(s.y-t.y, 2));
return d>0;
}
}
class Node {
#Override
public int hashCode() {
return this.index;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Node) {
return this.index == ((Node)obj).index;
}
return false;
}
int x, y, r;
int index;
int triggeredCount;
public Node(int x, int y, int r, int index) {
this.x = x;
this.y = y;
this.r = r;
this.index = index;
}
}
Output:
Deadliest node is: 2
Modify the code as per your needs. Do the null checks and error handling.
There might be some improvements to search with memorization in this problem - we don't really need to search again if the detonated bombs have been calculated before.
memory = [-1] * N
visited = [False] * N
def count_explosion(source):
if memory[source] != -1:
return memory[source]
accu = 1
visited[source] = True
for k in range(N):
if source == k:
continue
if adjacent[source][k] and not visited[k]:
if memory[k] != -1:
accu += memory[k]
else:
accu += count_explosion(k)
memory[source] = accu
return accu
max_num = 1
for i in range(N):
max_num = max(max_num, count_explosion(i))
return max_num
Note the adjacent is the matrix to store the directed graph, where we pre-process using the euclidean distance. We need a visited here as well to avoid cyclic cases.
I'm trying to solve this challenge which is to get the min cost of Knight's moves from a source to a destination in a (8*8) chess board and I'm getting a case that not working … I guess I messed up somewhere and I cant figure that out.
see image here
the full code
import java.util.ArrayList;
import java.util.List;
public class Solution {
static class Position{
public int x;
public int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int solution(int src, int dest) {
int min = 100000000;
int depth = 0;
Position source = new Position(0, 0), destination = new Position(0, 0);
int [][] board = getBoard(src, dest, source, destination);
if(arrived(source, destination)) return 0;
return solve(board, source, destination, (depth), min);
}
public static int[][] getBoard(int src, int dest, Position source, Position destination) {
int c = 0;
int [][] board = new int[8][8];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
if(c == src) {
board[i][j] = 1;
source.x = i;
source.y = j;
}else if(c == dest) {
board[i][j] = -1;
destination.x = i;
destination.y = j;
}else {
board[i][j] = 0;
}
c++;
}
}
return board;
}
public static int solve(int[][] board, Position position, Position destination, int depth, int min){
if(depth > min) {
return depth;
}
for(Position p: sort(getPossibleMoves(board, position), destination)){
if(arrived(p,destination)) {
return depth + 1;
}
board[p.x][p.y] = depth +2;
int cost = solve(board, p, destination, (depth + 1), min);
board[p.x][p.y] = 0;
if(cost < min){
min = cost;
}
}
return min;
}
public static List<Position> sort(List<Position> positions, Position dest) {
Position temp;
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int i = 0; i < positions.size() - 1; i++) {
if(distance(positions.get(i), dest) > distance(positions.get(i+1), dest)) {
temp = positions.get(i);
positions.set(i, positions.get(i+1));
positions.set(i+1, temp);
sorted = false;
}
}
}
return positions;
}
public static double distance(Position a, Position b) {
if(a.x == b.x && a.y == b.y) return 0;
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
public static boolean arrived(Position src, Position dest) {
return src.x == dest.x && src.y == dest.y;
}
public static List<Position> getPossibleMoves(int [][] board, Position current){
int [][] moves = {{1,2}, {2,1}, {-1,2}, {1,-2}, {-2,1}, {2,-1}, {-1,-2}, {-2,-1}};
List<Position> positions = new ArrayList();
for(int i = 0; i < moves.length; i++) {
int x = current.x + moves[i][0];
int y = current.y + moves[i][1];
if(x >= 0 && y >= 0 && x < board.length && y < board.length && board[x][y] <= 0)
positions.add(new Position(x, y));
}
return positions;
}
public static void main(String [] args) {
System.out.println(solution(0, 1));
}
}
so here is my approach :
we start from a position and we try all the possible moves (sorted by the nearest) till we find the destination and then do some kind of backtracking to see if there's a better way to get there at a low cost and return the minimum.
some rules I've set :
the board is represented by a matrix of integers ( full of zeros if empty)
the source is represented by 1
the destination is represented by -1
wherever the knight goes its going to be marked by an integer representing the cost (the start is 1 the second move will be 2 , third 3 and so on …)
let me break the code a little bit down to make it easier
we start from the function solution public static int solution(int src, int dest) which will initialize the board, set the source and destinatin positions, and return the cost using the solve(board, source, destination, (depth), min) function
the function public static int[][] getBoard(int src, int dest, Position source, Position destination) take the board, position … look trough all possible moves ( unmarked positions and sorted by the nearest) for that position and call recursively with a new position until it found the destination or the depth (witch is the cost) is bigger then the minimum that we already have
the function public static List<Position> getPossibleMoves(int [][] board, Position current) will return the 8 possible moves for knight from a position but only those who are not out of the board and are also unvisited ( unvisited will be 0 or -1 for the destination )
the function public static List<Position> sort(List<Position> positions, Position dest) will sort the possible moves by the nearest to the destination ( let's prioritize the nearest one)
please if you can help me figure out what's wrong or if you have another approach I'd really appreciate !
I have to do a method that will go through the matrix.I give the coordinates from the keyboard of the position [L, C], from where the extension will start.It will pass to the next value only if the next value is smaller than this.On the diagonals do not go!
PS: Sorry for my english
Like in image:
enter image description here
Three steps need to be done here:
// prepare output matrix and fill it with -1
int[][] outMatrix = prepareOut(inputArray.length, inputArray[0].length);
// call recursively method to mark cells starting from the initial coordinates
outMatrix = markCell(inputArray, outMatrix, line, column, 1);
// print output matrix
printOutput(outMatrix);
The most relevant method implementation may be like this:
static int[][] markCell(int[][] arr, int[][] out, int y, int x, int move) {
int val = arr[y][x];
if (out[y][x] == 0) {
return out;
} else if (out[y][x] < 0) {
out[y][x] = move;
}
// checking a cell above the current one (north)
if (y > 0 && out[y - 1][x] < 0) {
if (cellMarked(arr, out, y - 1, x, val, move)) {
out = markCell(arr, out, y -1, x, move + 1);
}
}
// checking a cell under the current one (south)
if (y < arr.length - 1 && out[y + 1][x] < 0) {
if (cellMarked(arr, out, y + 1, x, val, move)) {
out = markCell(arr, out, y +1, x, move + 1);
}
}
// checking a cell to the left of the current one (west)
if (x > 0 && out[y][x - 1] < 0) {
if (cellMarked(arr, out, y, x - 1, val, move)) {
out = markCell(arr, out, y, x - 1, move + 1);
}
}
// checking a cell to the right of the current one (east)
if (x < arr[0].length - 1 && out[y][x + 1] < 0) {
if (cellMarked(arr, out, y, x +1, val, move)) {
out = markCell(arr, out, y, x + 1, move + 1);
}
}
return out;
}
static boolean cellMarked(int[][] arr, int[][] out, int y, int x, int val, int move) {
final boolean marked = arr[y][x] <= val;
out[y][x] = marked ? move : 0;
return marked;
}
When printing the output matrix, you replace remaining -1 with 0:
static void printOutput(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
char c = arr[i][j] <= 0 ? '0' : '*';
System.out.print(c);
System.out.print('\t');
}
System.out.print('\n');
}
}
prepareOut may be implemented like this:
private static int[][] prepareOut(int rows, int cols) {
int [][] out = new int[rows][cols];
for(int[] row: out) {
Arrays.fill(row, -1);
}
return out;
}
I had to write a code to calculate the remainder using a certain way. I know that there are better ways to do it but that's how I have to proceed.
The if (rem(x - 1, y) + 1 == y) is making extra calls. As it enters there every time before getting to the last return, but it is an important step for my algorithm. I was wondering if there was any way to avoid it.
Also, I know that I have to check if y == 0; I am just trying to improve the performance for now.
Thanks
int rem(int x, int y)
{
if (x == 0)
{
return 0;
}
if (rem(x - 1, y) + 1 == y)
{
return 0;
}
return rem((x - 1), y) + 1;
}
I get 9 recursive calls for rem(3/2)
Sure, this is how you can make it much better.
int rem(int x, int y) {
if (x == 0) {
return 0;
}
int ret = rem(x - 1, y);
if (ret + 1 == y) {
return 0;
}
return ret + 1;
}
We can just call the function once and store its output in a variable.
Yeah sure, In java you do this in following way:
public static void main(String args[]) {
int remainder = remainder(3,2);
System.out.println(remainder);
}
static int remainder(int n1, int n2) {
int x;
x = n1;
if (x >= n2) {
x = x - n2;
remainder(x, n2);
}
return x;
}
Note: I've not added condition to check 0 in the code.
Hope this helps.
I have this class to hold two values:
public class Coord {
public int x;
public int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
}
I am trying to use it in a depth-first search algorithm:
x = this.move_to_x;
y = this.move_to_y;
Coord stack = new Coord(0, 0);
Stack<Coord> start = new Stack<Coord>();
Stack<Coord> visited = new Stack<Coord>();
start.push(stack);
visited.push(stack);
while (!start.empty()) {
Coord tmp = (Coord)start.pop();
int j,k;
j = tmp.x;
k = tmp.y;
// there is only 8 possible ways to go (the neighbors)
for (int a = -1; a < 2; a++) {
tmp.x = j + a;
for (int b = -1; b < 2; b++) {
if (a == 0 && b == 0) {
continue;
}
tmp.y = k + b;
if (tmp.x < 0 || tmp.y < 0) {
continue;
}
if (tmp.x > 5 || tmp.y > 5) {
continue;
}
if (tmp.x == x && tmp.y == y) {
System.out.println("end!");
return;
}
Coord push = new Coord(tmp.x, tmp.y);
System.out.println("visited: " + visited);
if (visited.search(push) == -1) {
System.out.println("added x " + push.x + " y " + push.y
+ " " + visited.search(push));
start.push(push);
visited.push(push);
} else {
System.out.println("visited x " + tmp.x + " y " + tmp.y
+ " index " + visited.search(push));
}
}
}
}
The problem is that the visited.search method is always returning -1. Here is the log:
visited: [Agent.ExampleAgent.Coord#1af6a711]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896]
added x 1 y 0 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e]
added x 1 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4]
added x 0 y 0 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4, Agent.ExampleAgent.Coord#262f6be5]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord#1af6a711, Agent.ExampleAgent.Coord#1c727896, Agent.ExampleAgent.Coord#5fbd8c6e, Agent.ExampleAgent.Coord#427a8ba4, Agent.ExampleAgent.Coord#262f6be5, Agent.ExampleAgent.Coord#199d4a86]
Note that the first element that is added to the visited stack is (0,1), however when it is searched for (0,1), later the method returns -1.
(Figured I'd post an answer outlining the progress we made in our chat discussion)
Assuming the following state of the Coord class:
public class Coord {
public int x;
public int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public boolean equals(Object obj){
if (obj == null)
return false;
if (obj.getClass() != Coord.class)
return false;
if (obj == this)
return true;
Coord a = (Coord)obj;
return (a.x == this.x && a.y == this.y);
}
#Override
public int hashCode() {
return x*17 + y*31;
}
#Override
public String toString() {
return "("+x+", "+y+")";
}
}
... that implements:
equals() as this is what stack search uses, according to its Javadoc
hashCode() as a best practice, accompanying equals()
toString() for clearer diagnostic output
The idea is to test the functionality of stack search in isolation from the rest of the code. If we can prove that stack search functions properly, then the problem is in elsewhere.
Proving that the stack search works can be done using a test class, such as this one:
public class CoordTest {
public static void main(String[] args) {
System.out.println("Running tests...");
System.out.println("Testing: equals");
Coord c1a = new Coord(2,3);
Coord c1b = new Coord(2,3);
check(c1a.equals(c1b));
System.out.println("Testing: not equals");
Coord c2a = new Coord(2,3);
Coord c2b = new Coord(6,8);
Coord c2c = new Coord(2,8);
Coord c2d = new Coord(6,3);
check(!c2a.equals(c2b));
check(!c2a.equals(c2c));
check(!c2a.equals(c2d));
System.out.println("Testing: not found in empty stack");
Stack<Coord> stack1 = new Stack<Coord>();
int result1 = stack1.search(c1a);
check(result1 == -1);
System.out.println("Testing: not found in non-empty stack");
Stack<Coord> stack2 = new Stack<Coord>();
stack2.push(new Coord(4,5));
stack2.push(new Coord(6,7));
int result2 = stack2.search(c1a);
check(result2 == -1);
System.out.println("Testing: found in non-empty stack");
Stack<Coord> stack3 = new Stack<Coord>();
stack3.push(new Coord(4,5));
stack3.push(new Coord(3,1));
stack3.push(new Coord(6,7));
int result3 = stack3.search(new Coord(3,1));
check(result3 == 2);
System.out.println("All tests completed successfully.");
}
private static void check(boolean condition) {
if (!condition) {
throw new RuntimeException("Condition failed!");
}
}
}
Output:
Running tests...
Testing: equals
Testing: not equals
Testing: not found in empty stack
Testing: not found in non-empty stack
Testing: found in non-empty stack
All tests completed successfully.
You need to override the equals() method so it returns true if x and y of the parameter are equal to the object's x and y values.
You should also override the hashCode() method so that it "agrees" with the equals() method.