首页 > 解决方案 > 作业问题,国际象棋皇后的可用字段

问题描述

我明天有学校作业,希望能得到一些帮助。我的任务是“创建一个程序,确定哪些棋盘区域可供女王从它所在的区域使用。棋盘显示为 8x8 矩阵。女王的位置从键盘输入到 [字母] [数字]。并将结果保存在一个字符串中。”

我有点坚持如何继续,我想我需要 8 种不同的 if。2 表示水平,2 表示垂直,4 表示对角线,但我不知道该怎么做。

int main()
{

    int horizontal,vertical,i,j,current;
    char poz;

    printf("Enter the horizontal position of queen(A-H)\n");
    scanf("%s", &poz);

    if(poz=='A')
    {
        horizontal=1;
    }
    else if (poz=='B')
    {
        horizontal=2;
    }   
    else if (poz=='C')
    {
        horizontal=3;
    }
    else if (poz=='D')
    {
        horizontal=4;
    }   
    else if (poz=='E')
    {
        horizontal=5;
    }
    else if (poz=='F')
    {
        horizontal=6;
    }
    else if (poz=='G')
    {
        horizontal=7;
    }
    else if (poz=='H')
    {
        horizontal=8;
    }

    printf("Enter the vertical position of queen(1-8)\n");
    scanf("%d",&vertical);

    int n=8,m=8;

    int chess[8][8]={
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    };

    printf("Queen pos is %c-%d",poz,vertical );


return 0;
}

标签: c

解决方案


强烈建议将水平和垂直位置的索引修改为 0...7 然后包括:(其中 'r' 是行,'c' 是列)

All positions in the column (0..7)/(c) where the queen is placed except (r)/(c) 

All positions in the row (r)/(0..7) where the queen is placed except (r)/(c)

然后从皇后位置开始 (r)/(c)

all successive positions (r+1)/(c-1) until edge of board
all successive positions (r+1)/(c+1) until edge of board
all successive positions (r-1)/(c-1) until edge of board
all successive positions (r-1)/(c+1) until edge of board

以上是一些“for()”语句,应该“相对”容易实现。


推荐阅读