N-Queens

Time Limit Exceeded, even for small judge. I guess it is because this solution needs n^2 space to store status for each Q placement.

public class Solution {
    ArrayList<String[]> res;

	public ArrayList<String[]> solveNQueens(int n) {
		// Start typing your Java solution below
		// DO NOT write main() function
		res = new ArrayList<String[]>();
		int[][] status = new int[n][n];
		generate(status, 0);
		return res;
	}

	public void generate(int[][] status, int row) {
		int n = status.length;
		if (row == n) {
			StringBuilder line;
			String[] matrix = new String[n];
			for (int r = 0; r < n; r++) {
				line = new StringBuilder("");
				for (int c = 0; c < n; c++) {
					if (status[r][c] == 1)
						line.append("Q");
					else
						line.append(".");
				}
				matrix[r] = line.toString();
			}
			res.add(matrix);
		} else {
			for (int i = 0; i < n; i++) {
				if (status[row][i] == 0) {
					int[][] temp = new int[n][n];
					for (int r = 0; r < n; r++) {
						for (int c = 0; c < n; c++) {
							if (r == row || c == i || (c - i == r - row) ||
									(i - c == r - row))
								temp[r][c] = 2;
							temp[r][c] = status[r][c];
						}
					}
					temp[row][i] = 1;
					generate(temp, row + 1);
				}
			}
		}
	}
}

This solution rocks!

public class Solution {
    ArrayList<String[]> res;

    // 检测前面行可以放Q的位置是不是和目前位置(place[row]=j)冲突,即位置[i][place[i]]和位置[row][j]是否冲突
    public boolean check(int row, int[] place) {
		for (int i = 0; i < row; ++i) {
			int diff = Math.abs(place[i] - place[row]);
			if (diff == 0 || diff == row - i)
				return false;
		}
		return true;
	}

    public void placeQueens(int row, int n, int[] place) {
		if (row == n) {
			String[] matrix = new String[n];
			StringBuilder line;
			for (int i = 0; i < row; i++) {
				line = new StringBuilder("");
				for (int j = 0; j < n; j++) {
    				if (j == place[i])
						line.append("Q");
					else
						line.append(".");
				}
				matrix[i] = line.toString();
			}
			res.add(matrix);
			return;
		}

		for (int col = 0; col < n; col++) {
			place[row] = col;
			if (check(row, place))
				placeQueens(row + 1, n, place);
		}
	}

	public ArrayList<String[]> solveNQueens(int n) {
		// Start typing your Java solution below
		// DO NOT write main() function
		int[] place = new int[n];
		// place[i] = j 表示第i行第j列可以放Q
		res = new ArrayList<String[]>();
		placeQueens(0, n, place);
		return res;
	}
}


你可能感兴趣的:(N-Queens)