2차원배열 오른쪽방향으로 돌면서 채우기 (Groovy)

Daum 쪽에 문제로 나왔다고 되어있어서 풀어본문제.


2차원 배열 오른쪽 방향으로 회전하면서 번호 채우기 

(방향전환을 4방향으로 다하면 미로찾기로 사용도 가능)


Robot 이 진행할 방향에 대해서 탐색, 정상일 경우 전진하는 방식 

--------------------------------------------------------------------------------------------------------

def arr = [[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],

  [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]

]


class Robot {

def arr

def locationCol = -1

def locationRow = 0

def stepCount = 0

def direction = 0


Robot(arr){

this.arr = arr

}

void execute(){

boolean result = true 

while(true){

result = findDirection()

if(result){

moveStep()

}else{

break;

}

}

for(int i=0; i < arr.size(); i++){

println arr[i]

}

}

int getStepCount(){

return stepCount

}

private boolean findDirection(){

//현재 방향으로 체크

boolean result = isEmpty()

if(!result){

direction = (++direction)%4

//방향전환하여 한번 더  체크

result = isEmpty()

}


return result

}


private void moveStep(){

switch(direction){

case 0:

locationCol++

break

case 1:

locationRow++

break

case 2:

locationCol--

break

case 3:

locationRow--

break

}

arr[locationRow][locationCol] = ++stepCount

}

private boolean isEmpty(){

boolean result = false

//해당 방향에 대해서 체크

switch(direction){

case 0://right

if(locationCol+1 < arr[0].size()){

result = arr[locationRow][locationCol+1] == -1 ? true : false

}

break;

case 1://down

if(locationRow+1 < arr.size()){

result = arr[locationRow+1][locationCol] == -1 ? true : false

}

break;

case 2://left

if(locationCol-1 >= 0){

result = arr[locationRow][locationCol-1] == -1 ? true : false

}


break;

case 3://up

if(locationRow-1 >= 0){

result = arr[locationRow-1][locationCol] == -1 ? true : false

}

break

}

return result

}

}



def robot = new Robot(arr)

robot.execute()