2017-12-26 22 views
0

현재 사용자가 8 Queens Problem에 대한 왕비를 배치해야하는 프로그램을 작성 중입니다. 지금은 거의 프로그램을 만들었지 만, 프로그램을 대각선으로 확인하는 방법에 집착하고 있습니다.8 Queens diagonal checking

이것은 (미완성) 코드 :

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
int check_r_c(int**chess,int*p,int N,int M) 
{ 
    int times=0; 
    for(int i=0; i<N; i++) 
    { 
     times=0; 
     for(int j=0; j<M; j++) 
     { 
      if(chess[i][j] == 1) 
       times++; 

     } 
     if(times != 1) 
     { 
      *p=1; 
      return 1; 
     } 
    } 
    for(int j=0; j<M; j++) 
    { 
     times=0; 
     for(int i=0; i<N; i++) 
     { 
      if(chess[i][j] == 1) 
       times++; 
     } 
     if(times != 1) 
     { 
      *p=1; 
      return 1; 
     } 
    } 
    *p=0; 
    return 0; 
} 
int main() 
{ 
    int N,M; 
    printf("Give the number of rows: \n"); 
    scanf("%d",&N); 
    printf("Give the number of columns: \n"); 
    scanf("%d",&M); 
    int**chess = malloc(N*sizeof(int)); 
    int i,j,ch; 
    int*ptr; 
    ptr=&ch; 
    if(chess==NULL) 
    { 
     printf("\nMemory cannot be allocated\n"); 
     return 1; 
    } 
    for(i=0; i<N; i++) 
    { 
     if((chess[i] = malloc(M*sizeof(int)))==NULL) 
     { 
      printf("\nMemory cannot be allocated\n"); 
      return 1; 
     } 
    } 
    for(int i=0; i<N; i++) 
     for(int j=0; j<M; j++) 
      chess[i][j]= 0; 
    for(int k=0; k<N; k++) 
    { 
     printf("Give the position of the %d queen\n",k+1); 
     scanf("%d",&i); 
     scanf("%d",&j); 
     if(chess[i][j] == 1) 
     { 
      printf("You cant put 2 queens in the same place!!!\n"); 
      return 0; 
     } 
     chess[i][j] = 1; 
    } 
    check_r_c(chess,ptr,N,M); 
    if(ch == 0) 
     printf("Solution is correct!"); 
    else 
     printf("Solution is incorrect!"); 
    for(int i=0; i<N; i++) 
     free(chess[i]); 
    free(chess); 
} 
+0

"나 갇혔어요."좋은 문제 설명이 아닙니다. 귀하의 질문은 구체적 무엇입니까? 시도해 봤니? 어떤 방법으로 작동하지 않습니까? – mkrieger1

답변

0

Firstable은 모든 X가 무엇인가? 둘째, 정크 코드를 쓰는 것이 좋지만 공유하는 경우 대부분의 독자가 쉽게 이해할 수 있도록 설명하거나 수정하십시오. 마지막으로, 귀하의 질문에 대답하기 위해, 그것을 할 수있는 한 가지 방법은 다음과 같습니다

for every cell on the left most column 
while there is a cell in position (column + i, line + i) (i starting at zero) 
if there is a queen count one 
end while 
if count is not one then return false 
end for 
1

배치 여왕 대각선 확인하는 논리는 ((p는, q는)에있는 모든 장소를 확인하는 것입니다 내가 P + , q + i) (여기서 p + i와 q + i는 모두 보드 내에 있음). 부정적인면은 (p-i, q-i)를 사용하라.