八皇后排序,92种

来源:互联网 发布:linux xargs cat命令 编辑:程序博客网 时间:2024/05/24 01:51


public class 八皇后 {


/**
* @param args
*/
 
       static int[][] map = new int[8][8];
       static int count = 0;
       public static void main(String[] args){
      
           Play(0);
       }



       private static void Play(int row)
       {
           for (int col = 0; col < 8; col++)
           {
               // 摆放前 先做判断
       
               if (Check(row, col) == true)
               {// 说明【row,col】这个点可以摆放皇后
                   map[row][col] = 1;


                   //  判断
                   if (row == 7)
                   {// 摆放好了  打印出来
                       Show();
                   }
                   else
                   {
                       Play(row + 1);
                   }
                   // 出问题了  撤销
                   map[row][col] = 0;
               }
           }
       }


       private static void Show()
       {
           count++;
           // 分开
           System.out.println("第"+count+"种摆法");
           
           // 行列
           for (int i = 0; i < 8; i++)
           {
               for (int j = 0; j < 8; j++)
               {
               System.out.print(map[i][j]);
                 
               }
               // 换一行
              System.out.println();
           }
       }


       private static boolean Check(int row, int col)
       {
           // 正上方
           for (int i = 0; i < row; i++)
           {
               if (map[i][col] == 1)
               {
                   return false;
               }
           }


           // 左斜上方
           for (int i=row,j=col; i>=0 && j>=0; i--,j--)
           {
               if (map[i][j] == 1)
               {
                   return false;
               }
           }


           // 右斜上方
           for (int i = row, j = col; i >= 0 && j < 8; i--, j++)
           {
               if (map[i][j] == 1)
               {
                   return false;
               }
           }


           // 说明可以摆放皇后
           return true;
       }






}
原创粉丝点击