N-Queens Problem Using Stacks Help

I'm trying to solve the N-Queens problem using Stacks. Quite frankly, I'm completely lost.
Here's the pseudocode from the book:
"Push information onto the stack indicating the first choice is a queen in row 1, column 1.
success = false;
while(!success && !s.isEmpty())
Check whether the most recent choice (on top of the stack) is in the same row, same column, or same diagonal as any other choices (below the top). If so, we say there is a conflict: otherwise, there is no conflict.
if (there is a conflict)
-Pop items off the stack until the stack becomes empty or the top of the stack is a choice that is not in column n. If the stack is now not empty, then increase the column number of the top choice by 1.
else if (no conflict and the stack size is n)
-Set success to true because we have found a solution to the n-queens problem.
else
-Push information onto the stack indicating tat the next choice is to place a queen at row number s.size()+1 and column number 1.
And here is my excuse for code so far. I have no idea how to check the diagonals, or how to even really make this work
{code}import java.util.Stack;
public class NQueens {
int row, column, n;
public NQueens(int n) {
row = 0;
column = 0;
n = n;
public Stack Solve(){
boolean success, conflict;
Stack<NQueens> Qs = new Stack<NQueens>();
if (Qs.size() == 0)
Qs.push(new NQueens(1));
success = false;
while (!success && !Qs.isEmpty())
if (Qs.peek().row == row)
conflict = true;
if (Qs.peek().column == column)
conflict = true;
if (conflict = true)
Qs.pop();
Qs.peek().column += 1;
else
if (!conflict && Qs.size() == n)
success = true;
else
Qs.push(new NQueens(Qs.size()+1));
return Qs;
{code}

First off I'll address this:
    int row, column, n;
    public NQueens(int n) {
        row = 0;
        column = 0;
        n = n; //here
    }Notice the last line of that. I get what you're trying to do, but think about what the compiler sees there. If you have two variables called 'n', one at the class level, and one at the method level, the compiler must have rules so it knows which one you're talking about. And if it follows those rules, then saying 'n' inside that method must always refer to the same n. Otherwise, how would it decide which one you're talking about? The rule here is that it uses the most local variable available to it, which in this case is your method parameter. So 'n = n' is setting the parameter equal to itself. To refer to the class variable n, use "this.n", like so:
this.n = n;Now that that's settled, let's address some logic. You'll need to figure out whether two Queens share a diagonal. I can think of at least a couple options for that. First, every time you look at a Queen you could loop through the entire board and make sure that if a piece is in r3c4, that no piece is in r2c3,r4c5,r5c6, etc. Or you could create a new variable for your class similar to your 'row' and 'column' variables that tracks the diagonal a piece is in. But that requires some calculating. And remember, there's 2 directions for diagonals, so you'll need 2 diagonal variables.
If these are your Row and Column values:
Row          Column
00000000     01234567
11111111     01234567
22222222     01234567
33333333     01234567
44444444     01234567
55555555     01234567
66666666     01234567
77777777     01234567And these are your diagonal values:
Diag 1                    Diag 2
0  1  2  3  4  5  6  7          7  6  5  4  3  2  1  0
1  2  3  4  5  6  7  8          8  7  6  5  4  3  2  1
2  3  4  5  6  7  8  9          9  8  7  6  5  4  3  2
3  4  5  6  7  8  9  10          10 9  8  7  6  5  4  3
4  5  6  7  8  9  10 11          11 10 9  8  7  6  5  4
5  6  7  8  9  10 11 12          12 11 10 9  8  7  6  5
6  7  8  9  10 11 12 13          13 12 11 10 9  8  7  6
7  8  9  10 11 12 13 14          14 13 12 11 10 9  8  7Then examine the relationship between Row(R), Column(C), and Diagonals 1 and 2 (D1/D2):
RC   D1,D2
00 = 0,7
01 = 1,6
02 = 2,5
03 = 3,4
04 = 4,3
05 = 5,2
06 = 6,1
07 = 7,0
10 = 1,8
11 = 2,7
12 = 3,6
13 = 4,5
14 = 5,4
15 = 6,3
16 = 7,2
17 = 8,1You'll notice that D1 is always the same as R + C. And D2 is always the same as C subtracted from 7 plus R, giving:
int d1 = row + column;
int d2 = (7 + row) - column;But remember, that 7 in the formula above, is based on how big your grid is. So whatever your 'N' is, whether its a 10x10 square or a 574x574 square, that 7 should be changed to (N-1)
So those could be your variables to track diagonals. What I'm noticing in your current code, is that you never change your row and column variables...so every Queen is always at r0c0. You should probably put values for those in your parameters for the constructor, in addition to n. Then the diagonals can be calculated from those.
Edited by: newark on Apr 17, 2008 10:46 AM

Similar Messages

  • I am having a problem using the help menu in Adobe elements 5

    I am having a problem using the help menu in Adobe elements number five.
    When I open the help menu, the dialogue box defaults to an unreadable display font. Is there any way to change that default font? Using the help menus to find a solution is not possible for I cannot read what it is displaying.

    For product, there is an option in preferences where we can set fonts. There are two options: One is application font and other is system font. I am talking about elements 8 which I have but not sure that will solve your problem which is help related.
    Hope Help in 5th version is html which opens in Browser? Please confirm.

  • Problem Using Stacks

    I need help using the Stacks feature in the Dock. When I drag a document out of the Finder and move it into a folder in the Dock, the entire document is removed from the Finder. No trace of the document is left in the Finder. Then, if I delete the document from the folder in the Dock the document is lost - it does not reappear in the Finder. What am I doing wrong? I would like to be able to use Stacks without risking the loss of my documents.

    The folders (Stacks) in the Dock are just aliases to actual folders somewhere on your computers.
    When you move something from a Folder in the Finder to a folder (stack) in the Dock, the file gets moved to the folder that is represented by the Stacked folder.
    If you right-click (or ctrl-click) on the stack icon in the dock, you can choose "Show in Finder," and it will open the actual folder that is being aliased by the stack.
    So, if you've moved a file to a folder in the Dock, and then deleted it from the folder that is represented by the Stack on the Dock, you will have deleted the actual file.
    What is shown on the face of the Dock are aliases (shortcuts) to actual items. If you remove one of the aliases, the original is not deleted. If you remove what is in the aliases on the Dock, you will delete the original, as that is what is there.

  • Problem using stacks in CS4

    So I want to try to edit in  stacks but cant seem to get it to work. my  understanding is the the usual command is file, scripts, load into stack  and then once your files load you go file, scripts, statistics, my  problem is that there is not file, scripts, statistics for me. I'm using  CS4 extended so I should have it. My layer, smart objects, stack mode  is always grayed out too. (weather I convert the top file to a smart  object, or all the files or select all and then convert to smart object,  which flattens the layers). So Im wondering if there is some setting I  have changed that would prevent me form using stacks? or if im just  missing something, thanks Im using windows 7, PS CS4 version 11.0.2
    Thanks ahead of time

    Are you using CS4, or CS4 Extended?  The stacks are only creatable in extended.

  • Problem using Stack

    how can i store characters in a Stack using the Stack class . I see that the Stack class takes only Objects so how can i make it take a character.
    Thanks in Advance

    Hi!
    The Character class wrap a char. So, when you store one char in the Stack you must put:
    stack.push(new Character(myChar));
    and, to get the char put:
    char c = ((Character)stack.pop()).charValue();
    Hope, this help!

  • FLASH PROBLEM USING ("STACKED")

    HI TO ALL
    USING WHEN NEW BLOCK INSTANCE TRIGGER IN THE BLOCK > THE FLASH WORK BUT I HAVE TO CLICK FIRST THE OCX BEFORE IT APEARS>
    BUT IN CONTENT IT WORKS BUT IN STACKED NEED TO CLICK BEFORE IT WORKS>> WHAT DO YOU THINK IS WRONG>>
    I TRY IN FORMS< WHEN NEW FORMS INSTANCE> IT WORKS BUT IF I PUT IN ONE TRIGGER FOR TWO OCX IT WONT WORK>>>> ANY SOLUTION? PLZ HELP
    TNX IN ADVANCE

    Hi
    Yes ocx in blocks..and forms6i run in client server..
    My question is, i used trigger, when new form instance in the block... then the ocx is in the canvass type=stacked. when i open, it wont apear the flash i have to click the ocx to play the flash... but i need to used the stacked ..i have multiple ocx in stacked, in content.
    in content it works but in stacked have to click to play...

  • Problems with the help menu.

    Hi. I'm a new iMac user and have had problems using the help menu on my computer. Every time I click on help and search a topic I get a blank untitled window. Nothing ever opens up in the window and then the spinning beach ball comes up. It is only in the blank window and I am still able to use the computer normally. I am unable to close or force quit the program and have to restart to get rid of it. I have called tech support and spent over an hour on the phone with no help and ended up reinstalling the operating system. Still having the same problem. Anyone have some advice or have had a similar problem?

    Welcome to Apple Discussions!
    Try reindexing the hard drive via Apple menu -> System Preferences -> Spotlight.
    Drag the hard drive into the Privacy section, and the select it in that section, and select the minus sign in the bottom left corner below the field holding the drive.
    Click then on Spotlight every half hour to wait until the Indexing status no longer shows up.
    If Help still doesn't come up entirely, try clicking on the clear jewel in the upper right corner of the Help menu. It may reveal the search field. If it doesn't, quit from the Help Viewer application menu, and then go to com.apple.helpviewer.plist and delete it. Help should then load normally.
    If it still doesn't, try repairing permissions with Applications -> Utilities -> Disk Utility.
    In the end, if that still doesn't work, let us know, and we might suggest something else.

  • OS is Mountain Lion, upgraded no problems, used an external Hard drive for my time machine, now my iPhoto will not show any of my photo's or ay new ones I import! Help please!!

    OS is Mountain Lion, upgraded no problems, used an external Hard drive for my time machine, now my iPhoto will not show any of my photo's or ay new ones I import! Help please!!

    Do you get this window when you hold down the Command+Option keys and launch iPhoto?
    If not then you're not holding down both keys long enough.
    OT

  • Until recently I was able to send images in the body of my Yahoo emails. Now, I am getting the message "This message has been truncated", and the email does not go through. I do not have this problem using IE. Could you please help? Thank you.

    Until recently I was able to send images in the body of my Yahoo emails. Now, I am getting the message "This message has been truncated", and the email does not go through. I do not have this problem using IE. Could you please help? Thank you.

    Try this -> http://support.apple.com/kb/TA38632?viewlocale=en_US

  • Powerpoint presentation I have stored in icloud until recently were syncing to Keynote on my iPad with no problem.  Now when I open Keynote on my iPad there is nothing.  I could use some help with this problem.

    powerpoint presentation I have stored in icloud until recently were syncing to Keynote on my iPad with no problem.  Now when I open Keynote on my iPad there is nothing.  I could use some help with this problem.

    Morning AndreD86,
    Thanks for using Apple Support Communities.
    These articles explain exactly what is backed up by using their method.
    iTunes: About iOS backups
    http://support.apple.com/kb/ht4946
    and
    iCloud: Backup and restore overview
    http://support.apple.com/kb/ht4859
    Also we want to double-click the Home button and swipe the Task Bar to the right.
    Then make sure the button on the far left of Task Bar is not muted.
    Best of luck,
    Mario

  • I am using the trial version of CC and cannot get the auto blend layers working despite following many videos on youtube etc. I have selected all layers but no matter which order I select etc all I get is an output of the first file in the stack - help!!

    I am using the trial version of CC and cannot get the auto blend layers working despite following many videos on youtube etc. I have selected all layers but no matter which order I select etc all I get is an output of the first file in the stack - help!!

    <moved from Adobe Creative Cloud to Photoshop General Discussion>

  • I am having problems using mov files imported into a project. I get the message "Not rendered" in the Canvas and clip won't play. Can anyone help?

    I am having problems using mov files imported into a project. I get the message "Not rendered" in the Canvas and clip won't play. Can anyone help?

    When clips won't play without rendering in the Timeline, it usually means that the clip's specs don't match the Sequence settings.
    A .mov file could be made from any number of codecs; the QuickTime Movie designation is merely a container for video files of all kinds.  Since FCE only works with the QuickTime DV codec and the Apple Intermediate Codec (AIC) natively, if your mov files aren't one of those two, you need to convert them PRIOR to importing into your FCE project.
    -DH

  • My ipad is connected to my wifi, however when i try to sign my ipad into facetime is says that it is having trouble connecting. I use my wifi to get on the internet on my iPad so i have no idea what the problem is. Help Me

    My ipad is connected to my wifi, however when i try to sign my ipad into facetime is says that it is having trouble connecting. I use my wifi to get on the internet on my iPad so i have no idea what the problem is. Help Me

    - Did it successfully connect to the network before?
    - Do other devices successfully connect to the network now?
    - Does you iPod successfully connect to other networks?
    - Have you reset your iPod?
    Press and hold the On/Off Sleep/Wake button and the Home
    button at the same time for at least ten seconds, until the Apple logo appears.
    - Reset network connections: Settings>General>Reset>Reset Network Settings
    - Powered off and then back on your router
    - The troubleshooting here:
    iPhone and iPod touch: Troubleshooting Wi-Fi networks and connections
    -When you restored you iPod did you restore to factory defaults/new iPod?  If not try that.
    - If you look at the network properties on the iPod what IP address is assigned when you think you are connected but actually have no internet connection.  If it starts with 169 then the iPod never connected to the router, the 169 address are self assigned.

  • SOS problem using one Entity bean for editing records. please help me

    Hello
    I have one great problem using one entity bean 2.1 and i am working with this problem several days and i dont solve it.
    i am using this jb 2.1 for add new records to one oracle database and for editing records.
    I have one great problem for editing records
    I have one objets that is as one of my database table. (PersonaObj.java)
         //personaObj.java
         public class PersonaObj implements Serializable{
              private Integer id_persona; //this ishte database table autonumeric
              private java.lang.String nombre;
              now the set/get methods.
         One field of this objets (bean) is the primary key of the table, and this field is one part of the pk from the entity bean.
         From one session bean i call the entity bena passing the objet
         into the entity bean (interface) i have one methods:
              public getPersona getT56aaat04();
         public void setPersona(PersonaObj obj);
         into the entitybean bean i have:
         public PersonaEntityPK ejbCreate(PersonaObj obj) throws CreateException {
              this.setT56aaat04(obj);
              public abstract Integer getId_persona();
         public abstract void setId_persona(Integer Id_persona);
         public abstract java.lang.String getNombre();
         public abstract void setNombre(java.lang.String Nombre);
         public PersonaObj getPersona() {
              PersonaObj obj = new PersonaObj();
              obj.setId_persona(getId_persona());
              obj.setNombre(getNombre());
              return obj;
         public void setPersona(PersonaObj obj) {
              setId_persona(obj.getId_persona());
              setNombre(obj.getNombre());
    But i have one graet problem.
    adding new record to the database i runs well but if i want to edit one recor appears this error:
    => Error <=
    java.rmi.RemoteException: EJB Exception: ; nested exception is: javax.ejb.EJBException: EJB Exception: : java.lang.IllegalStateException:[EJB:010144]The setXXX method for a primary key field may only be called during ejbCreate.
    at PersonasEJB_a43o8n__WebLogic_CMP_RDBMS.setId_persona(PersonasEntityEJB_a43o8n__WebLogic_CMP_RDBMS.java:328)
    at PersonasEntityBean.setPersona(PersonasEntityBean.java:114)
    at PersonasEntityEJB_a43o8n_ELOImpl.setPersona(PersonasEntityEJB_a43o8n_ELOImpl.java:45)
    at PersonasSessionBean.editarPersona(PersonasSessionBean.java:849)
    at PersonasSessionBean_bszo9t_EOImpl.editarPersona(PersonasSessionBean_bszo9t_EOImpl.java:208)
    at PersonasSessionBean_bszo9t_EOImpl_WLSkel.invoke(Unknown Source)
    into the session bean i make this (the session recibes one PersonaObj obj):
    T56aContactosEntityLocal personaLocal ;
                   try {
                        personaLocal = personaHome.findByPrimaryKey(new T56aContactosEntityPK(obj.getId_a04()));
                        T56aaat04Obj objTmp = new T56aaat04Obj();
                        objTmp.setAp1_a04(obj.getAp1_a04());
                        objTmp.setEstado_a04("false");
                        personaLocal.setT56aaat04(obj);
    Please can you help me to solve this problem?

    Hello Werner,
    The mappings seem to be alright at a first glance.
    Have you tried out un- and redeploying your application? Sometimes values appear to be cached in the server. So if you have deployed the application before you entered DB_BANK as alias this might solve the problem...
    BR
    Daniel

  • Having problem while using Stacked Column Chart.

    Hi,
    my result set is as below
    STAGE OPERATION
    TOTAL PCS
    1 SIDE SEAM
    6714
    2 BIND BOTTOM
    4522
    2 SLEEVE ATTACH
    6105
    3 BIND TOP(E/N)
    3781
    5 SLEEVE HEM
    3277
    6 BIND TACK-2
    1173
    6 TACK-2
    1277
    6 TACK-4
    268
    I need to display it on the screen by using stacked column chart. I mean XAxis as "STAGE" YAxis as "TOTAL PCS" and "OPERATION" as series. I used DataBIndCrossTable as 
    chProd.DataBindCrossTable(dtView, "OPERATION", "STAGE", "TOTAL PCS", "Label=TOTAL PCS");
    But, the results in the chart is displaying it in the first STAGE it self. I mean xaxis value 1 has all the yaxis value.
    Can anyone please help me to get the results as first image?
    I'm anable to attach the related images here.
    Thanks in advance.
    Regrds,
    Rajesh.

    Got the answer.
    Just added 
    chProd.AlignDataPointsByAxisLabel();
    Regards,
    Rajesh

Maybe you are looking for

  • How to use MathType in Visio 2013

    How to type equations in MS Visio? I am using equation editor 3.0, but it is very hard to keep size of different objects as same. And I just know that equation editor is replaced by MathType, but I couldn't find it in my viso 2013, and no information

  • Hebrew Font Problem

    Hello all! I have some problem with the Hebrew version of Nokia PC Suite... the fonts of the main menu, of the contacts and messages are very small and wrong fonts... I have attached a picture that shows the issue... Thanks! 

  • "iTunes could not connect to the iPod "iPod touch" because an unknown error

    I bought an ipod touch today, hooked it up, and got this error "iTunes could not connect to the iPod "iPod touch" because an unknown error occurred 0xE8000001)." <Edited by: Host> Has anyone else had an experience like this?

  • Redeploy all changes in an ESS DC?

    Using the NWDS, how do I redeploy all the custom modifications in a single ESS Development Component (for example, essusbank).  I know how to do the checkout..activiate process but if I do that for one object, will it pick up my modifications through

  • Mountain lion doesn't shut down.(Macbook pro with retina)

    I had tried 3 times delete "com.apple.dock.plist" and conduct "sudo reboot /w", deleted "itunes help" from login item, It work for one day or two then problem come back again. Anyone could help me ?