codewars020: The Clockwise Spiral 數字順時針螺旋矩陣

https://www.codewars.com/kata/536a155256eb459b8700077e/train/javajava

//-- https://www.codewars.com/kata/536a155256eb459b8700077e/train/java
public class TheClockwiseSpiral{
  private static final int UP = 0;
  private static final int DOWN = 1;
  private static final int LEFT = 2;
  private static final int RIGHT = 3;
  public static int[][] createSpiral(int N){
    int[][] data = new int[N][N];
    int toward = RIGHT;
    for(int num=1,i=0,j=0; num <= N*N; num++){
      data[i][j] = num;
      switch(toward){
      case UP:
        if(i == 0 || data[i - 1][j] != 0){
          toward = RIGHT;
          j++;
        }else{
          i--;
        }
        break;
      case DOWN:
        if(i == N - 1 || data[i + 1][j] != 0){
          toward = LEFT;
          j--;
        }else{
          i++;
        }
        break;
      case LEFT:
        if(j == 0 || data[i][j - 1] != 0){
          toward = UP;
          i--;
        }else{
          j--;
        }
        break;
      case RIGHT:
        if(j == N -1 || data[i][j + 1] != 0){
          toward = DOWN;
          i++;
        }else{
          j++;
        }
        break;
  
      }
    }
    return data;
  }
}

Reference:.net

http://bbs.csdn.net/topics/360184555code

相關文章
相關標籤/搜索