Java for LeetCode 051 N-Queens
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的更多相关文章
- Java for LeetCode 216 Combination Sum III
		Find all possible combinations of k numbers that add up to a number n, given that only numbers from ... 
- Java for LeetCode 214 Shortest Palindrome
		Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ... 
- Java for LeetCode 212 Word Search II
		Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ... 
- Java for LeetCode 211 Add and Search Word - Data structure design
		Design a data structure that supports the following two operations: void addWord(word)bool search(wo ... 
- Java for LeetCode 210 Course Schedule II
		There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ... 
- Java for LeetCode 200 Number of Islands
		Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ... 
- Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
		Say you have an array for which the ith element is the price of a given stock on day i. Design an al ... 
- Java for LeetCode 154 Find Minimum in Rotated Sorted Array II
		Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ... 
- Java for LeetCode 153 Find Minimum in Rotated Sorted Array
		Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ... 
随机推荐
- Oracle使用JDBC进行增删改查
			数据库和表 create table USERS( USERNAME VARCHAR2(20) not null, PASSWORD VARCHAR2(20))alter table USERS ... 
- 关于OOM那些事儿
			最近在aliyun上crontab里放的一个java脚本把机器搞翻了,ssh连不上T_T 发现OOM了,真是无语.并不懂Java的内存模型,转一篇备用吧. 转载自:http://www.cnblogs ... 
- BZOJ-1699 Balanced Lineup   线段树区间最大差值
			Balanced Lineup Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 41548 Accepted: 19514 Cas ... 
- SpringAOP
			首先导包, 我用的是Spring4.0.4;需要这三个包 Spring-AOP-4.0.4.REALEASE.jar + Spring-aspect-4.0.4.REALEASE.jar +aspec ... 
- asp.net input怎么获取值
			前台: <input type="hidden" name="content" value="content"> 后台: Req ... 
- SmartImageView&常见的开源代码
			1)说明: 该控件实现图片的显示----网络路径也可以显示出来---加载完成之后 就可以 缓存到内存里面! 
- jquery插件实现上下滑动翻页效果
			<!DOCTYPE > <meta charset="utf-8" /> <head> <title>测试jquery</ti ... 
- CentOS 6.4安装Apache+MySQL+PHP的图文教程
			LAMP 实际上就是 Linux.Apache.MySQL.PHP 四个名称的缩写,当然最后一个 “P” 还有其他说法是 Perl 或者 Python.不用多说了,本文讲解的就是 Linux.Apac ... 
- tomcat架构
			很多开源应用服务器都是集成tomcat作为web container的,而且对于tomcat的servlet container这部分代码很少改动.这样,这些应用服务器的性能基本上就取决于Tomcat ... 
- WebRequest中的工厂方法模式
