function NQueens( x )
tic;
global t;
t=0;
s(x)=0;
for i=1:x
    s(1)=i;
    main(s);
end
disp('Number of states: ');
disp(t);
disp('Runtime: ');
disp(toc);
end

function main( s )
global t;
m=unsafe(s);
temp=0;
for i=1:length(s)
    if(s(i)>0)
        temp=i+1;
    end
end
for i=1:length(s)
    if  m(temp,i) < 1
        s(temp)=i;
        if(s(length(s))>0)
            m(length(s),s(length(s)))=8;
            t=t+1;
            disp(m);
        else
            main(s);
        end
    end
end
end

function a=unsafe(s)
a=zeros(length(s));
for j=1:length(s)
    if (s(j)>0)
        for i=1:length(s)
            a(j,i)=1;
            if(i>j)
                a(i,s(j))=1;
            end
            if(i>j && s(j)-i+j>0)
                a(i,s(j)-i+j)=1;
            end
            if(i>j && s(j)+i-j<(length(s)+1))
                a(i,s(j)+i-j)=1;
            end
        end
        a(j,s(j))=8;
    end
end
end