deriving time-complexity of nqueens problem - algorithm

Can anyone prove/derive the time complexity of my nqueens solution approach?
I am going through each and every position on the grid and if it is possible to place a queen there, then, I am calculating solution by first placing the queen and then unplacing the queen, else I move on.
Code:
bool notinrow(int row,int col,vector<string> tra)
{
for(int i=0;i<tra.size();i++)
{
if(tra[row][i]=='Q' & i!=col)
return false;
}
return true;
}
bool notincol(int row,int col,vector<string> tra)
{
for(int j=0;j<tra.size();j++)
{
if(tra[j][col]=='Q' & j!=row)
return false;
}
return true;
}
bool notindiag1(int r,int c, vector<string> tra)
{
int i=r-1;
int j=c-1;
while(i>=0 & j>=0)
{
if(tra[i][j]=='Q')
return false;
i--;j--;
}
return true;
}
bool notindiag2(int r, int c,vector<string> tra)
{ int i=r-1;
int j=c+1;
while(i>=0 & j<totqueens)
{
if(tra[i][j]=='Q')
return false;
i--;j++;
}
return true;
}
void nqueens(int number,vector<string> tra,int currqueens)
{
if(currqueens==totqueens)
{
bhej.push_back(tra);
return ;
}
if(number==totiter)
return;
int x=number/totqueens;
int y=number%totqueens;
if(ispossible(x,y,tra))
{
tra[x][y]='Q';
nqueens(number+1,tra,currqueens+1);
tra[x][y]='.';
nqueens(number+1,tra,currqueens) ;
}
else
nqueens(number+1,tra,currqueens);
}```

Related

Doubly Linked List insert function

I am having problem with this code.Can someone help me to fix it ?
Problem is in insert function especially with malloc(allocating).I don't understand why I cannot malloc.It is not printing the debug text.
#include<stdlib.h>
#include<stdio.h>
#define TRUE 1
#define FALSE 0
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct ListRecord
{
struct Node *head;
struct Node *tail;
int length;
};
typedef struct ListRecord *DoubleList;
DoubleList createList()
{
return NULL;
}
DoubleList MakeEmptyList(DoubleList l)
{
l = (struct ListRecord*)malloc(sizeof(struct ListRecord));
if(l==NULL)
{
printf("Memory allocation failed!");
}
else
{
l->head->next=NULL;
l->head->prev=NULL;
l->tail=l->head;
l->length=0;
}
}
DoubleList InsertListAtPosition(DoubleList l,int pos,int val)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
printf("debug");
if(newNode==NULL)
{
printf("debug");
newNode->data=val;
newNode->next=NULL;
newNode->prev=NULL;
if(pos > l->length+1)
{
pos=l->length+1;
}
else if(pos==l->length+1)
{
struct Node *iterator=l->head;
while(iterator->next != NULL)
{
iterator=iterator->next;
}
iterator->next=newNode;
newNode->prev=iterator;
newNode->next=NULL;
}
else
{
struct Node* iterator=l->head;
int i;
for(i=0;i<pos;i++)
iterator=iterator->next;
newNode->next=iterator->next;
newNode->prev=iterator;
iterator->next->prev=newNode;
iterator->next=newNode;
}
l->length++;
}
else
{
printf("Memory allocation failed!");
}
}
int DeleteListAtPosition(DoubleList l,int pos)
{
int value;
if(l==NULL)
{
printf("List is empty");
return 0;
}
else
{
if(pos==1)
{
struct Node* iterator=l->head;
value=iterator->data;
free(iterator);
return value;
}
else
{
struct Node* iterator=l->head;
int i;
for(i=1;i<pos;i++)
iterator=iterator->next;
if(iterator->next==NULL)
{
value=iterator->data;
free(iterator);
return value;
}
else
{
iterator->prev->next=iterator->next;
iterator->next->prev=iterator->prev;
free(iterator);
}
}
}
}
void printList(DoubleList l) {
struct Node* temp = l->head;
printf("Forward: ");
while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
DoubleList myList;
int exit,pos,value;
char command;
myList=createList();
exit=FALSE;
while(!exit)
{
fflush(stdin);
printf("\nMenu:\n m)akeEmpty\n i)nsert\n e)xit\n");
scanf("%c", &command);
fflush(stdin);
switch(command)
{
case 'm':
myList = MakeEmptyList(myList);
break;
case 'i':
printf("Enter position to be added: ");
scanf("%d",&pos);
printf("Enter value to be added: ");
scanf("%d",&value);
InsertListAtPosition(myList,pos,value);
//printList(myList);
break;
case 'e':
exit = TRUE;
break;
default:
printf("command not recognized\n");
break;
}
}
printf("\n\n");
system("PAUSE");
return 0;
}
Here is the working code,
#include<stdlib.h>
#include<stdio.h>
#include <bits/stdc++.h>
#define TRUE 1
#define FALSE 0
using namespace std;
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct ListRecord
{
struct Node *head;
struct Node *tail;
int length;
};
typedef struct ListRecord *DoubleList;
DoubleList createList()
{
return NULL;
}
DoubleList MakeEmptyList()
{
DoubleList l;
l = (struct ListRecord*)malloc(sizeof(struct ListRecord));
if(l==NULL)
{
printf("Memory allocation failed!");
}
else
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = NULL;
newNode->prev = NULL;
l->head = newNode;
l->tail=l->head;
l->length=0;
}
return l;
}
DoubleList InsertListAtPosition(DoubleList l,int pos,int val)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if(newNode != NULL)
{
newNode->data=val;
newNode->next=NULL;
newNode->prev=NULL;
if(pos > l->length)
{
pos=l->length+1;
}
else if(pos==l->length)
{
struct Node *iterator=l->head;
while(iterator->next != NULL)
{
iterator=iterator->next;
}
iterator->next=newNode;
newNode->prev=iterator;
newNode->next=NULL;
}
else
{
struct Node* iterator=l->head;
int i;
for(i=0;i<pos;i++)
iterator=iterator->next;
newNode->next=iterator->next;
newNode->prev=iterator;
iterator->next->prev=newNode;
iterator->next=newNode;
}
l->length++;
}
else
{
printf("Memory allocation failed!");
}
}
int DeleteListAtPosition(DoubleList l,int pos)
{
int value;
if(l==NULL)
{
printf("List is empty");
return 0;
}
else
{
if(pos==1)
{
struct Node* iterator=l->head;
value=iterator->data;
free(iterator);
return value;
}
else
{
struct Node* iterator=l->head;
int i;
for(i=1;i<pos;i++)
iterator=iterator->next;
if(iterator->next==NULL)
{
value=iterator->data;
free(iterator);
return value;
}
else
{
iterator->prev->next=iterator->next;
iterator->next->prev=iterator->prev;
free(iterator);
}
}
}
}
void printList(DoubleList l) {
struct Node* temp = l->head;
printf("Forward: ");
while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
DoubleList myList;
int exit,pos,value;
char command;
exit=FALSE;
while(!exit)
{
fflush(stdin);
printf("\nMenu:\n m)akeEmpty\n i)nsert\n e)xit\n");
scanf("%c", &command);
fflush(stdin);
switch(command)
{
case 'm':
myList = MakeEmptyList();
break;
case 'i':
printf("Enter position to be added: ");
scanf("%d",&pos);
printf("Enter value to be added: ");
scanf("%d",&value);
if(myList == NULL) {
myList = MakeEmptyList();
}
InsertListAtPosition(myList,pos,value);
//printList(myList);
break;
case 'e':
exit = TRUE;
break;
default:
printf("command not recognized\n");
break;
}
}
printf("\n\n");
system("PAUSE");
return 0;
}
So you were making the following mistakes,
Your MakeEmptyList method is returning nothing, it should return l.
Inside you insert you were checking with length + 1, instead of only length, so it was causing pointer related errors.

Time and space complexity of if(!areAllArrayElementsZero())

How can I calculate the time and space complexity of a program(pseudo code) as follows:
function(){
if(!areAllArrayElementsZero()){
if(hasAnyOdd()){
decreaseOneFromFirstOddElementInArray()
} else {
divideAllArrayElementByTwo()
}
}
}
Here areAllArrayElementsZero(),hasAnyOdd(),divideAllArrayElementByTwo() has the complexity O(n). Any leads would help. Actually I was designing the solution to this problem.
Here is the Java equivalent of the above pseudo code, I've designed:
package competitive;
/*
* Problem: http://www.geeksforgeeks.org/count-minimum-steps-get-given-desired-array/
*/
class formarray{
private static int[] elem;
private static boolean areAllZeros(){
for(int i=0; i<elem.length;i++){
if(elem[i]>0){
return false;
}
}
return true;
}
private static boolean hasAnyOdd(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0){
// odd element discovered
return true;
}
}
return false;
}
private static boolean decreaseFirstOddByOne(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0) {
// odd element discovered
elem[i]-=1;
// return true if one is decreased from first odd element
return true;
}
}
return false;
}
private static void DivideArrayElementsByTwo(){
for(int i=0; i<elem.length;i++){
// we are not checking element to be even as it has already been checked
elem[i] = elem[i]/2;
}
}
public static void main(String args[]){
elem = new int[args.length];
// assign values
for(int i=0;i<args.length;i++){
elem[i] = Integer.parseInt(args[i]);
}
int steps=0;
while(!areAllZeros()){
if(hasAnyOdd()){
// the array has odd members
if(decreaseFirstOddByOne()){
steps++;
}
} else {
DivideArrayElementsByTwo();
steps++;
}
}
System.out.println("Total steps required: "+steps);
}
}
There are exactly 4 paths of execution; sum up the cost of each, take the largest.
Or realize there are no loops and each path has a finite number of O(n) elements, making the whole thing O(n).

Optimizations for Solitaire SPOJ

Problem Code: SOLIT
Problem Link: http://www.spoj.com/problems/SOLIT/
I tried solving the SPOJ problem Solitaire. However, I ended up with a TLE (Time Limit Exceeded). My current solution is taking around 2 seconds to execute. I have no idea how to optimize my solution further in order to reduce the time. So, I would be grateful for any help in this regard.
Link to my solution: https://ideone.com/eySI91
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Solitaire {
enum Direction {
TOP, RIGHT, DOWN, LEFT;
};
static class Piece {
int row, col;
public Piece(int row, int col) {
this.row = row;
this.col = col;
}
#Override
public boolean equals(Object o)
{
if (!(o instanceof Piece))
return false;
Piece p = (Piece)o;
return (row==p.row && col==p.col);
}
#Override
public int hashCode()
{
return (row*10 + col)%11;
}
}
static class State {
HashSet<Piece> pieces;
public State() {
pieces = new HashSet<>(11);
}
public State(State s) {
pieces = new HashSet<>(11);
for (Piece p: s.pieces)
pieces.add(new Piece(p.row, p.col));
}
#Override
public boolean equals(Object o) {
if (!(o instanceof State))
return false;
State s = (State) o;
if (pieces.size()!=s.pieces.size())
return false;
for (Piece p: pieces)
{
if (!s.pieces.contains(p))
return false;
}
return true;
}
#Override
public int hashCode() {
final int MOD = 1000000007;
long code = 0;
for (Piece p: pieces) {
code = (code + p.hashCode())%MOD;
}
return (int) code;
}
#Override
public String toString()
{
String res = "";
for (Piece p: pieces)
res = res + " (" + p.row + ", " + p.col + ")";
return res;
}
public int getCloseness(State s)
{
int medianRow=0, medianCol=0, sMedianRow=0, sMedianCol=0;
for (Piece p: pieces)
{
medianRow+=p.row;
medianCol+=p.col;
}
medianRow/=4;
medianCol/=4;
for (Piece p: s.pieces)
{
sMedianRow+=p.row;
sMedianCol+=p.col;
}
sMedianRow/=4;
sMedianCol/=4;
int closeness = ((sMedianCol-medianCol)*(sMedianCol-medianCol)) + ((sMedianRow-medianRow)*(sMedianRow-medianRow));
return closeness;
}
}
static State makeMove(State curr, Piece piece, Direction dir, HashSet<State> visited) {
if (dir == Direction.TOP) {
if (piece.row==1)
return null;
if (curr.pieces.contains(new Piece(piece.row-1, piece.col)))
{
if (piece.row==2 || curr.pieces.contains(new Piece(piece.row-2, piece.col)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row-2, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row-1, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else if (dir == Direction.RIGHT) {
if (piece.col==8)
return null;
if (curr.pieces.contains(new Piece(piece.row, piece.col+1)))
{
if (piece.col==7 || curr.pieces.contains(new Piece(piece.row, piece.col+2)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col+2));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col+1));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else if (dir == Direction.DOWN) {
if (piece.row==8)
return null;
if (curr.pieces.contains(new Piece(piece.row+1, piece.col)))
{
if (piece.row==7 || curr.pieces.contains(new Piece(piece.row+2, piece.col)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row+2, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row+1, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else // dir == Direction.LEFT
{
if (piece.col==1)
return null;
if (curr.pieces.contains(new Piece(piece.row, piece.col-1)))
{
if(piece.col==2 || curr.pieces.contains(new Piece(piece.row, piece.col-2)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col-2));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col-1));
if (visited.contains(newState))
return null;
else
return newState;
}
}
}
static boolean isReachableInEightMoves(State src, State target) {
Queue<State> q = new LinkedList<>();
HashSet<State> visited = new HashSet<>();
int closeness = src.getCloseness(target);
q.add(src);
int moves = 0;
while (!q.isEmpty() && moves <= 8) {
int levelNodes = q.size();
for (int i = 0; i < levelNodes; i++) {
State curr = q.remove();
if (curr.equals(target))
return true;
if (moves==8)
continue;
visited.add(curr);
for (Piece p: curr.pieces)
{
State newState = makeMove(curr, p, Direction.TOP, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.RIGHT, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.DOWN, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.LEFT, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
}
}
moves++;
}
return false;
}
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(FileDescriptor.out), "ASCII"));
CustomScanner sc = new CustomScanner();
int t = sc.nextInt();
long start = System.currentTimeMillis();
while (t-- > 0) {
State src = new State(), target = new State();
for (int i = 0; i < 4; i++) {
src.pieces.add(new Piece(sc.nextInt(), sc.nextInt()));
}
for (int i = 0; i < 4; i++) {
target.pieces.add(new Piece(sc.nextInt(), sc.nextInt()));
}
if (isReachableInEightMoves(src, target))
out.write("YES");
else
out.write("NO");
out.newLine();
}
long end = System.currentTimeMillis();
out.write("Time to execute = " + Double.toString((end-start)/1000d));
out.flush();
}
static class CustomScanner {
BufferedReader br;
StringTokenizer st;
public CustomScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
Some notes regarding the implementation:-
I am just doing a simple bfs traversal where each node is a state of
the board.
I have defined a function called getCloseness() which measures the closeness of two different states. It is basically the square of the distance between the centroids of the two states. A centroid of a state is the sum of all row values of each piece divided by 4 and the same for columns.
After calculating each state, I am checking if the closeness of this new state is lesser than or equal to the current closeness.
If it is not closer, then I will simply discard the new discovered state.
If it is closer, then I will update the closeness value and insert this new state into the Queue for future processing.
This process terminates when either the queue becomes empty or a state is discovered which is same as the target state.
The above approach takes approximately 1-3 seconds for cases where a minimum of 7 moves are required. I would be grateful if you can tell me how I can further optimize this solution.
The expected time according to the problem is 0.896s.

Hierholzer algorithm to find eulerian path [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have implemented hierholzer algorithm to find eulerian path in a graph using two stacks. Below is my implementation. There is some runtime error, will be glad if somebody could help
#include<bits/stdc++.h>
using namespace std;
stack<int> result;
stack<int> temp;
class graph
{
int v;
list<int> *adj;
public:
graph(int v)
{
this->v=v;
adj=new list<int> [v];
}
~graph()
{
delete []adj;
}
void add_edge(int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void remove_edge(int u, int v);
int start_vertex();
void print_euler_path(int u);
bool allvisited();
};
int graph::start_vertex()
{
int u=0;
for(int u=0;u<v;u++)
{
if(adj[u].size() & 1)
break;
}
return u;
}
bool graph::allvisited()
{
for(int i=0;i<v;i++)
{
if(adj[i].size()>0)
{
list<int>::iterator it;
for(it=adj[i].begin();it!=adj[i].end();it++)
{
if(*it!=-1)
return false;
}
}
}
return true;
}
void graph::remove_edge(int u,int v)
{
list<int>::iterator i;
i=find(adj[u].begin(),adj[u].end(),v);
*i=-1;
i=find(adj[v].begin(),adj[v].end(),u);
*i=-1;
}
void graph::print_euler_path(int u)
{
temp.push(u);
list<int>::iterator i;
int flag=0;
if(allvisited())
return;
for(i=adj[u].begin();i!=adj[u].end();i++)
{
if(*i!=-1)
{
cout<<"S";
remove_edge(u,*i);
print_euler_path(*i);
}
}
if(!temp.empty())
{
int k=temp.top();
temp.pop();
result.push(k);
if(!temp.empty())
print_euler_path(temp.top());
}
}
int main()
{
graph g(6);
g.add_edge(0,1);
g.add_edge(1,2);
g.add_edge(2,3);
g.add_edge(3,0);
g.add_edge(5,1);
g.add_edge(5,2);
g.add_edge(4,1);
g.add_edge(4,2);
int u=g.start_vertex();
g.print_euler_path(u);
while(!result.empty())
{
cout<<result.top()<<" ";
result.pop();
}
return 0;
}
For exact logic you can refer http://iampandiyan.blogspot.in/2013/10/c-program-to-find-euler-path-or-euler.html
I don't think that these lines do what you want:
remove_edge(u,*i);
print_euler_path(*i);

2D vector subscript out of range

It says vector subscript out of range when achieving if statement. I think I added extra int to floor, or extra floor vector to 2D vector. I am using VS 2010(C++)
I tried to find it on other questions but not succeeded.
bool is_perfect_square(int);
int main()
{
int cust;
vector<int>floor;
vector<vector<int>>hotel;
floor.push_back(0);
hotel.push_back(floor);
hotel[0][0]=1;
for(cust=2; ; cust++)
{
for(int i=0; i<=hotel.size(); i++)
{
if(is_perfect_square(cust+hotel[i][floor.size()]))
{
floor.push_back(0);
hotel[i][cust]=cust;
break;
}
else
{
hotel.push_back(floor);
hotel[hotel.size()][0]=cust;
}
}
}
int sum=0;
for(int a=1; a<=hotel.size(); a++)
{
for(int b=1; b<=floor.size(); b++)
{
if(pow(a-1,2)+pow(b-1,2)==14234886498625)
sum+=hotel[a-1][b-1];
}
}
cout<<sum<<endl;
system("pause");
return 0;
}
bool is_perfect_square(int n)
{
int root=floor(sqrt(n));
return n == root * root;
}
I put my answers in the comments.
bool is_perfect_square(int);
int main()
{
int cust;
vector<int>floor;
vector<vector<int>>hotel;
floor.push_back(0);
hotel.push_back(floor);
hotel[0][0]=1;
// you may not be able to get out of this loop
// because the "break" below only exits one level of the loop.
for(cust=2; ; cust++)
{
// this should be changed to "i<hotel.size()",
// because the subscript of a vector ranges from 0 to its size minus one.
for(int i=0; i<=hotel.size(); i++)
{
// here "floor.size()" should be floor.size() - 1, the same reason.
if(is_perfect_square(cust+hotel[i][floor.size()]))
{
floor.push_back(0);
hotel[i][cust]=cust;
break;
}
else
{
hotel.push_back(floor);
hotel[hotel.size()][0]=cust;
}
}
}
int sum=0;
for(int a=1; a<=hotel.size(); a++)
{
for(int b=1; b<=floor.size(); b++)
{
if(pow(a-1,2)+pow(b-1,2)==14234886498625)
sum+=hotel[a-1][b-1];
}
}
cout<<sum<<endl;
system("pause");
return 0;
}
bool is_perfect_square(int n)
{
int root=floor(sqrt(n));
return n == root * root;
}

Resources