Skip to content

Instantly share code, notes, and snippets.

@benelog
Last active January 15, 2018 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benelog/e58577dc57b6641cb104 to your computer and use it in GitHub Desktop.
Save benelog/e58577dc57b6641cb104 to your computer and use it in GitHub Desktop.
나선형배열 문제
package problems;
import static java.util.Arrays.*;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.function.Consumer;
/**
* Java8 이용, for/if문 없이 구현
*
*/
public class Matrix {
static class Position {
int x;
int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public boolean isIn(int width, int height) {
return ((x >= 0) && (x<width) && (y >=0) && (y<height));
}
}
enum Direction {
RIGHT(pos -> pos.x++),
DOWN (pos -> pos.y--),
LEFT (pos -> pos.x--),
UP (pos -> pos.y++);
static {
RIGHT.next = DOWN;
DOWN.next = LEFT;
LEFT.next = UP;
UP.next = RIGHT;
}
private Direction next;
private Consumer<Position> mover;
private Direction (Consumer<Position> mover) {
this.mover = mover;
}
public void move(Position position) {
mover.accept(position);
}
public Direction getNext() {
return next;
}
}
private static final int UNREACHED = -1;
private int height = 0;
private int width = 0;
private int[][] space;
public Matrix(int height, int width){
this.height = height;
this.width = width;
space = new int[height][width];
stream(space).forEach(row -> fill(row, UNREACHED));
locate();
}
public void print(){
List<int[]> rows = asList(space);
Collections.reverse(rows);
rows.forEach(row -> {
stream(row).forEach(n -> System.out.print(n + "\t"));
System.out.println();
}
);
}
private void locate() {
Position pos = new Position(0, height-1); // start Position
space[pos.y][pos.x] = 0;
Direction direction = Direction.RIGHT;
while(move(pos ,direction)) direction = direction.getNext();
}
private boolean move(Position pos, Direction direction){
int step = space[pos.y][pos.x];
boolean moved = false;
while(isMovable(pos, direction)) {
direction.move(pos);
space[pos.y][pos.x]= ++step;
moved = true;
}
return moved;
}
private boolean isMovable(Position pos, Direction direction){
Position nextPos = new Position(pos.x, pos.y);
direction.move(nextPos);
return (nextPos.isIn(width, height)) && (space[nextPos.y][nextPos.x] == UNREACHED);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
sc.close();
new Matrix(row,col).print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment