Java for LeetCode 051 N-Queens

來源:互聯網
上載者:User

標籤:

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens‘ placement, where ‘Q‘ and ‘.‘ both indicate a queen and an empty space respectively.

解題思路:經典的八皇后問題,由於之前在《JAVA語言程式設計》中exerice6-22中做過這種問題,代碼直接拿來修改下即可,JAVA實現如下:

static public List<String[]> solveNQueens(int n) { List<String[]> list=new ArrayList<String[]>(); if(n==1){ String[] str={"Q"}; list.add(str); return list; }// int count = 0;     int[] queens = new int[n]; // queens are placed at (i, queens[i])    for (int i = 0; i < n; i++)      queens[i] = -1;     queens[0] = 0;     int k = 1;    while (k >=0) {      int j = findPosition(k, queens,n);      if (j ==-1) {        queens[k] = -1;        k--; // back track to the previous row      } else {        queens[k] = j;        if (k == n-1) {//          count++;           String[] queenArray=new String[n];          for(int i=0;i<n;i++){          StringBuilder sb=new StringBuilder();          for(int j2=0;j2<n;j2++){          if(j2==queens[i])          sb.append(‘Q‘);          else sb.append(‘.‘);          }          queenArray[i]=new String(sb);          }          list.add(queenArray);        }         else {          k++;        }      }    }     return list;   }  public static int findPosition(int k, int[] queens,int n) {    int start = queens[k] == -1 ? 0 : queens[k] + 1;    for (int j = start; j < n; j++) {      if (isValid(k, j, queens,n))        return j;     }    return -1;  }  public static boolean isValid(int k, int j, int queens[],int n) {    for (int i = 0; i < k; i++)      if (queens[i] == j)        return false;    for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)      if (queens[row] == column)        return false;    for (int row = k - 1, column = j + 1; row >= 0 && column <= n-1; row--, column++)      if (queens[row] == column)        return false;    return true;  }

 

Java for LeetCode 051 N-Queens

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.