boolean ready;

void main() {
    ready = false;
    handleRow(0);
}

void handleRow(int row) {
    int size = getSize();
    
    if (row == size) { // fertig
        ready = true;
        return;
    }
    
    if (rowOccupied(row)) {
        handleRow(row + 1);
        return;
    }
      
    for (int c=0; c<size; c++) {
        if (movePossible(row, c)) {
            setQueen(row, c);
            handleRow(row + 1);
            if (ready) {
                return; // Lsung gefunden
            } else {  // Backtracking
                removeQueen(row, c);
            }
        }
    }
}

boolean movePossible(int row, int col) {
    return !colOccupied(col) && 
           !diagonalsOccupied(row, col);
}

boolean rowOccupied(int row) {
    int size = getSize();
    for (int c = 0; c < size; c++) {
        if (isQueen(row, c)) {
            return true;
        }
    }
    return false;
}


boolean colOccupied(int col) {
    int size = getSize();
    for (int r = 0; r < size; r++) {
        if (isQueen(r, col)) {
            return true;
        }
    }
    return false;
}

boolean diagonalsOccupied(int row, int col) {
    int size = getSize();
    
    int r = row;
    int s = col;
    while ((r >= 0) && (s >= 0)) {
        if (isQueen(r, s)) {
            return true;
        }
        r--;
        s--;
    }
    
    r = row;
    s = col;
    while ((r >= 0) && (s < size)) {
        if (isQueen(r, s)) {
            return true;
        }
        r--;
        s++;
    }
    
    r = row;
    s = col;
    while ((r < size) && (s >= 0)) {
        if (isQueen(r, s)) {
            return true;
        }
        r++;
        s--;
    }
    
    r = row;
    s = col;
    while ((r < size) && (s < size)) {
        if (isQueen(r, s)) {
            return true;
        }
        r++;
        s++;
    }

    return false;
}
