vendredi 12 avril 2019

Access diagonals of a particular cell in matrix

Solving problem of 8 queens i am actually stuck in how to access the diagonals of a particular cell to set it to 1 when placing a queen. There is simple logic for the cells which are in vertical or horizontal of the selected cell where queen has to be placed.

Here is the code of my function to set the cells for the queen to 1 which that queen can attack.

static int[][] SetPos(int csp[][],int row,int col){
        int count = 0, n = csp.length;
        for (int i = 0; i < csp.length; i++) {
            for (int j = 0; j < csp.length; j++) {
                if(i==row || j==col){
                    csp[i][j]=1;
                }

                if(row==col && i==j){
                    //csp[row][col]=1;
                    csp[i][j]=1;
                }
                if(row+count==i && col+count==j){
                    csp[i][j]=1;
                }

            }
            count++;
        }

        return csp;
    }

How can this condition be improved:

if(row+count==i && col+count==j){
      csp[i][j]=1;
}

So that i get result for cell(5,5) as :

 1  0  0  0  0  1  0  0 
 0  1  0  0  0  1  0  0 
 0  0  1  0  0  1  0  0 
 0  0  0  1  0  1  0  1 
 0  0  0  0  1  1  1  0 
 1  1  1  1  1  1  1  1 
 0  0  0  0  1  1  1  0 
 0  0  0  1  0  1  0  1 

not like this :

 1  0  0  0  0  1  0  0 
 0  1  0  0  0  1  0  0 
 0  0  1  0  0  1  0  0 
 0  0  0  1  0  1  0  0 
 0  0  0  0  1  1  0  0 
 1  1  1  1  1  1  1  1 
 0  0  0  0  0  1  1  0 
 0  0  0  0  0  1  0  1 

Backtracking is not the concern right now.

Aucun commentaire:

Enregistrer un commentaire