Runtime error of N-queens of unput "3" but works fine on my PC


  • 0
    Z
    vector<vector<string>> solveNQueens(int n) {
    int *rows = new int[n];
    int *diagnals1 = new int[2 * n - 1];
    int *diagnals2 = new int[2 * n - 1];
    int *positions = new int[n];
    int *lastPlaced = new int[n];
    
    int i = 0, j = 0;
    
    for (i = 0; i < n; i++) {
    	rows[i] = 0;
    	diagnals1[i] = 0;
    	diagnals2[i] = 0;
    	positions[i] = -1;
    	lastPlaced[i] = -1;
    }
    for (; i < 2 * n; i++) {
    	diagnals1[i] = 0;
    	diagnals2[i] = 0;
    }
    
    int current = 0;
    vector<string> solutions;
    vector<vector<string>> result;
    string temp;
    while (current >= 0) {
    	while (positions[current] + 1 < n) {
    		positions[current] += 1;
    		if (rows[positions[current]] == 0 && diagnals1[n + current - positions[current] - 1] == 0 && diagnals2[2 * n - positions[current] - current - 2] == 0) {
    			if (lastPlaced[current] != -1) {
    				rows[lastPlaced[current]] = 0;
    				diagnals1[n + current - lastPlaced[current] - 1] = 0;
    				diagnals2[2 * n - lastPlaced[current] - current - 2] = 0;
    			}
    			if (current == n - 1) {
    				solutions.clear();
    				for (i = 0; i < n; i++) {
    					temp.clear();
    					for (j = 0; j < n; j++) {
    						if (positions[i] == j) {
    							temp.append("Q");
    						}
    						else {
    							temp.append(".");
    						}
    					}
    					solutions.push_back(temp);
    				}
    				result.push_back(solutions);
    			}
    			else {
    				lastPlaced[current] = positions[current];
    				rows[positions[current]] = 1;
    				diagnals1[n + current - positions[current] - 1] = 1;
    				diagnals2[2 * n - positions[current] - current - 2] = 1;
    				current++;
    			}
    		}
    	}
    	if (positions[current] + 1 == n) {
    		if (lastPlaced[current] != -1) {
    			rows[lastPlaced[current]] = 0;
    			diagnals1[n + current - lastPlaced[current] - 1] = 0;
    			diagnals2[2 * n - lastPlaced[current] - current - 2] = 0;
    			lastPlaced[current] = -1;
    		}
    		positions[current] = -1;
    		current--;
    	}
    }
    
    return result;
    

    }

    I simply use Depth-first Search to solve the problem. There are n possible positions for each of the n columns. The code works fine on my PC but gets a Runtime Error with input 3.


  • 0
    M

    I get a Runtime Error with input 2, also my code works well on my PC....


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.