2009-11-05 8 views
2

지루했기 때문에 작은 콘솔 지뢰 찾기 게임을 만들었고 writting하는 동안 요소의 벡터로 표시되는 크기 * 크기의 행렬에서 요소의 인접 위치를 찾아야 만했습니다. 크기 값을 보유하는 하나의 변수. 필자는 이웃 요소의 실제 값을 반환하고 싶지 않았지만 위치를 공용 함수로 사용할 수 있도록했습니다 (그렇지 않으면 클라이언트가 광산이있는 위치를 볼 수 있습니다 : P).매트릭스의 이웃 위치 찾기

필드 당량 0 크기 당량 3 예를 들어, 함수 반환한다 {1, 3, 4}

1 0 0 0 1 0 
0 0 0 => 1 1 0 
0 0 0 0 0 0 

그런데, 이것은 기본적은 다음과 같다 :

vector<int> adjecantPositions(int field, int size) 
{ 
    int row = field/size; 
    int col = field % size; 
    vector<int> result; 

    /* 
     1 0 0 
     1 0 0 
     1 0 0 
    */  
    if (col > 0) 
    { 
     result.push_back(calcField(row, col-1, size)); 

     if (row > 0)  
      result.push_back(calcField(row-1, col-1, size)); 
     if (row < size - 1) 
      result.push_back(calcField(row+1, col-1, size)); 
    } 

    /* 
     0 0 1 
     0 0 1 
     0 0 1 
    */ 
    if (col < size - 1) 
    { 
     result.push_back(calcField(row, col+1, size)); 

     if (row > 0)  
      result.push_back(calcField(row-1, col+1, size)); 
     if (row < size - 1) 
      result.push_back(calcField(row+1, col+1, size)); 

    } 

    /* 
     0 1 0 
     0 0 0 
     0 1 0 
    */ 
    if (row > 0) 
     result.push_back(calcField(row-1, col, size)); 
    if (row < size - 1) 
     result.push_back(calcField(row+1, col, size)); 

    return result; 
} 

calcField을 (int, int, int)는 단지 좌표를 필드 번호 (row * size + col)로 변환합니다.

이 방법은 빠르지 만 우아하지는 않으며 좋은 방법이 있습니다. 어떤 아이디어?

답변

1

예, 코드가 끔찍합니다. 여기

for (int dx=-1; dx<=1; dx++) 
    for (int dy=-1; dy<=1; dy++) 
    if (dx || dy){ 
     int x = row+dx, y=col+dy; 
     if (x >= 0 && x < size && y >= 0 && y < size) 
     result.push_back(calcField(x, y, size)); 
    } 
+0

이 코드는 잘못된 결과를 반환하지만 난 당신이 경기장 주위에 형성된 3 × 3 행렬을 횡단하는 ... 나는이 생각하지 않았다는 것을 이해할 수없는 것을 볼 수 :이 더 읽을 수 생각합니다. – schmrz

0

를 파벨의 솔루션을 고정 코드입니다 : 여기에 더 나은 시도 (고정, 죄송합니다)의

for (int drow = -1; drow <= 1; drow++) 
{ 
    int rrow = row + drow; 

    for (int dcol = -1; dcol <= 1; dcol++) 
    { 
     int rcol = col + dcol; 

     if (rrow >= 0 && rrow < size && rcol >= 0 && rcol < size 
      && !(rrow == row && rcol == col)) 
      result.push_back(calcField(rrow, rcol, size)); 
    } 
} 
1

왜 좌표에 대한 객체를 사용하지?

struct Coords 
{ 
    int row; 
    int col; 

    Case(row, col) : row(row), col(col) {} 
    bool isValid(int size) 
    { 
    return row >= 0 && col >= 0 && row < size && col < size; 
    } 
} 

vector<Coords> adjecantPositions(const Coords & field, int size) 
{ 
    vector<Coords> result; 
    for(int drow = -1; drow <= 1; ++drow) 
    { 
    for(int dcol = -1; dcol <= 1; ++dcol) 
    { 
     Coords current(field.row + drow, field.col + dcol); 
     if(current.isValid(size)) 
     { 
     result.push_back(current); 
     } 
    } 
    } 
    return result; 
}