图,DFS,8皇后问题 思路或者算法

必须用C或C++,用图结构和DFS解决8皇后问题,需要思路或者算法设计,刚学数据结构这门课,有些问题不会

 #include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;

int mat[8][8];

int ans = 0;
bool check(int row,int col)
{
    for(int i=0;i<row;i++)
    {
        //不能同列
        if(mat[i][col])
        {
            return false;
        }
        //不能在同一对角线
        for(int j=0;j<8;j++)
        {
            if(mat[i][j])
            {
                if( fabs(i - row) - fabs(j - col) == 0)
                {
                    return 0;
                }
                else
                {
                    break;
                }
            }
        }
    }
    return true;
}

int dfs(int row)
{
    if(row>=8)
    {
        ans++;
        for(int i=0;i<8;i++)
        {
            for(int j=0;j<8;j++)
            {
                printf("%d ",mat[i][j]);
            }
            printf("\n");
        }
        printf("\n");
    }

    for(int col=0;col<8;col++)
    {
        if(check(row,col))
        {
            mat[row][col] = 1;
            dfs(row + 1);
            mat[row][col] = 0;
        }
    }
}
int main()
{
    memset(mat,0,sizeof(mat));

    dfs(0);

    printf("total = %d\n",ans);
    return 0;
}

八皇后问题:http://baike.xsoftlab.net/view/199.html

不要教条了,楼上给的都是经典实现了。不见得邻接表或邻接矩阵能表示一张图,二维数组也能表示一张图的。只有算法挑数据结构,没有定死数据结构去挑算法的。