Skip to content

Instantly share code, notes, and snippets.

@bchetty
Created May 24, 2013 21:26
Show Gist options
  • Select an option

  • Save bchetty/5646622 to your computer and use it in GitHub Desktop.

Select an option

Save bchetty/5646622 to your computer and use it in GitHub Desktop.
Spiral Walking in a rectangular grid.
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] = "&gt;";
} else {
y--;
res[x][y] = "&gt;";
}
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] = "&lt;";
} else {
y++;
res[x][y] = "&lt;";
}
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