Last active
January 4, 2016 12:59
-
-
Save yekmer/8625133 to your computer and use it in GitHub Desktop.
Solution for a question, that there is a chesstable 4x4, you are starting from left lower corner to right upper corner. You should print all alternative paths to go, and solution should be recursive? (There are 2 different solutions below. 2nd solution below is a simple search algorithm, 1st solution is a simpler DFS solution)
This file contains 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
public class ChessPath { | |
private static int length = 4; | |
public static void main(String[] args) { | |
String headStr = ""; | |
getPath(1, 0, false, headStr); | |
getPath(0, 1, true, headStr); | |
} | |
public static void getPath(int xC, int yC, boolean upD, String path) { | |
if(xC == length || yC == length) return; | |
if(upD) path += "U"; | |
else path += "R"; | |
if(xC == (length - 1) && xC == yC) { | |
System.out.println(path); | |
return; | |
} | |
getPath(xC + 1, yC, false, path); | |
getPath(xC, yC + 1, true, path); | |
} | |
} |
This file contains 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
public class PathFinding { | |
static int GRID_LENGTH = 4; | |
static PathFinding pathFinding = new PathFinding(); | |
public static void main(String[] args) { | |
String str = ""; | |
Node head = pathFinding.new Node(0, 0, str); | |
searchNode(head); | |
} | |
public static void searchNode(Node node) { | |
List<Node> nodeList = node.getAvailableNodes(); | |
if(nodeList.size() == 0) { | |
System.out.println(node); | |
return; | |
} else { | |
for(Node iNode : nodeList) { | |
searchNode(iNode); | |
} | |
} | |
} | |
class Node { | |
int rightC = 0; | |
int upC = 0; | |
String str = ""; | |
public Node(int rightC, int upC, String str) { | |
this.rightC = rightC; | |
this.upC = upC; | |
this.str = str; | |
} | |
public List<Node> getAvailableNodes() { | |
List<Node> availableNodes = new ArrayList<Node>(); | |
if(rightC < GRID_LENGTH - 1) { | |
String newStr = new String(str + "R"); | |
Node rightNode = new Node(rightC + 1, upC, newStr); | |
availableNodes.add(rightNode); | |
} | |
if(upC < GRID_LENGTH - 1) { | |
String newStr = new String(str + "U"); | |
Node upNode = new Node(rightC, upC + 1, newStr); | |
availableNodes.add(upNode); | |
} | |
return availableNodes; | |
} | |
@Override | |
public String toString() { | |
return str; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment