Created
May 24, 2013 21:26
-
-
Save bchetty/5646622 to your computer and use it in GitHub Desktop.
Spiral Walking in a rectangular grid.
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
| public class SpiralWalking { | |
| public static void main(String[] args) { | |
| SpiralWalking sw = new SpiralWalking(); | |
| String res[][] = sw.walkSpirally(10,10); | |
| for(int i=0;i<10;i++) { | |
| System.out.println(); | |
| for(int j=0;j<10;j++) { | |
| System.out.print(res[i][j] + " "); | |
| } | |
| } | |
| } | |
| public String[][] walkSpirally(int row, int col) { | |
| boolean[][] matrix = new boolean[row][col]; | |
| String[][] res = new String[row][col]; | |
| for(int i=0;i<row;i++) { | |
| java.util.Arrays.fill(matrix[i], false); | |
| } | |
| boolean east = true; | |
| boolean south = false; | |
| boolean west = false; | |
| boolean north = false; | |
| int x=0,y=0; | |
| while(true) { | |
| if(east) { | |
| if(y < (col-1) && !matrix[x][y]) { | |
| res[x][y] = "-"; | |
| matrix[x][y] = true; | |
| y++; | |
| } else { | |
| if(!matrix[x][y]) { | |
| res[x][y] = ">"; | |
| } else { | |
| y--; | |
| res[x][y] = ">"; | |
| } | |
| x++; | |
| if(x >= row || matrix[x][y]) { | |
| break; | |
| } | |
| east = false; | |
| south = true; | |
| } | |
| } else if(south) { | |
| if(x < (row-1) && !matrix[x][y]) { | |
| res[x][y] = "|"; | |
| matrix[x][y] = true; | |
| x++; | |
| } else { | |
| if(!matrix[x][y]) { | |
| res[x][y] = "v"; | |
| } else { | |
| x--; | |
| res[x][y] = "v"; | |
| } | |
| y--; | |
| if(y < 0 || matrix[x][y]) { | |
| break; | |
| } | |
| south = false; | |
| west = true; | |
| } | |
| } else if(west) { | |
| if(y > 0 && !matrix[x][y]) { | |
| res[x][y] = "-"; | |
| matrix[x][y] = true; | |
| y--; | |
| } else { | |
| if(!matrix[x][y]) { | |
| res[x][y] = "<"; | |
| } else { | |
| y++; | |
| res[x][y] = "<"; | |
| } | |
| x--; | |
| if(x < 0 || matrix[x][y]) { | |
| break; | |
| } | |
| west = false; | |
| north = true; | |
| } | |
| } else if(north) { | |
| if(x > 0 && !matrix[x][y]) { | |
| res[x][y] = "|"; | |
| matrix[x][y] = true; | |
| x--; | |
| } else { | |
| if(!matrix[x][y]) { | |
| res[x][y] = "^"; | |
| } else { | |
| x++; | |
| res[x][y] = "^"; | |
| } | |
| y++; | |
| if(y <= col || matrix[x][y]) { | |
| break; | |
| } | |
| north = false; | |
| east = true; | |
| } | |
| } | |
| } | |
| return res; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment