Eight Queens problem (search and backtracking, output by the column)

[Title] Description
placing eight queens on a chess board, the requirements can not be directly eat each other between every two queens.

[Enter]
(no)

[Output]
by all eight queens problem solution of a given sequence and output formats (see sample).

[] Input sample
(no)
[] sample output
. No.. 1
. 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0. 1
0 0. 1 0 0 0 0 0
0 0 0 0 0 0 0. 1
0. 1 0 0 0 0 0 0
0 0 0. 1 0 0 0 0
0 0 0 0 0. 1 0 0
0 0 0 0 0 0 0. 1
. No. 2
. 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0. 1
0 0 0. 1 0 0 0 0
0 0 0 0 0. 1 0 0
0 0 0 0 0 0 0. 1
0. 1 0 0 0 0 0 0
0 0 0 0. 1 0 0 0
0 0. 1 0 0 0 0 0
... omitted below

Topic Analysis:
The biggest problem exasperating place is in columns output , at the beginning how it is no law in the order shown in the output of the board!
We can first create a two-dimensional array to store a different type of board, then create a one-dimensional array b [i] denotes the i column has not occupied (ie, put the Queen). Established c [i + j] and d [i-j + 7] represents a diagonal array have not been accounted for. (+7 to prevent negative array index programmed)
and then start the search from placing first queen, the queen finish put eight or output can not meet its placement on the back one step and choose a new placement.
Code:

#include<iostream>
#include<cmath>
using namespace std;
int sum=0;
int a[9][9];//储存棋盘种类
int c[10],d[10];//分别控制两条对角线
int b[10];//占领第几列。
void search(int);
void print();
int main()
{
    search(1);
    return 0;
}
void search(int i)
{
    for(int j=1;j<=8;j++)
    {
        if(b[j]==0&&c[i+j]==0&&d[i-j+7]==0)
        {
            a[i][j]=1;
            b[j]=1;
            c[i+j]=1;
            d[i-j+7]=1;
            if(i==8) print();
            else search(i+1);
            b[j]=0;
            c[i+j]=0;
            d[i-j+7]=0;
            a[i][j]=0;
        }
    }
}
void print()
{
    sum++;
    cout<<"No. "<<sum<<endl;
    for(int i=1;i<=8;i++)
    {
        for(int j=1;j<=8;j++)
            cout<<a[j][i]<<" ";//按列输出
        cout<<endl;
    }
}

result:

输出:
No. 1
1 0 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