寻找二维数组的邻居 [英] Finding the neighbors of 2D array

查看:144
本文介绍了寻找二维数组的邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由75列组成的75格的二维网格,我在用户点击时绘制了2种颜色(红色和蓝色)的符号,它工作正常,但我困住了一个主要问题,我想找到那些邻居符号:当用户点击一个单元格时,它会打印一个符号(椭圆形),现在我希望该单击也检查其邻居是否单元格被占用或空,如果占用,使用哪个符号。

我发现下面的算法似乎符合需求,但无法弄清楚如何适应我的代码:

  private static int [] [] array = new int [3] [3]; 

private static void initialiseArray(){
int counter = 1; (int col =; col <3; col ++){
array [row] [col] = counter;
for(int row =; row< 3; row ++)
counter ++;




$ b public static void main(String args []){
initialiseArray(); (int row =; row< 3; row ++){
for(int col =; col< 3; col ++){
System.out.print(array [row] [COL]);
if(col == 2){
System.out.println(\\\
);
}
}
}
neighbors();
}

public static void neighbors(){
int posX = 2;
int posY = 2; (int row = posX-1; row <= posX + 1; row ++){
for(int col = posY-1; col< = posY + 1; col ++)的

){
if(!(posX == row&& posY == col)&& row> =&& col> =&& row< 3&& amp ; col< 3){
System.out.println(array [row] [col]);
}
}
}
}

是我的代码,我需要你帮我解决这个问题。

  public final class Pha扩展JFrame {

public static int ROWS = 75;
public static int COLS = 75;


public static int cellSize = 15;
public static int canvasWidth = cellSize * COLS +(ROWS * 4);
public static int canvasHeight = cellSize * ROWS;
public static int gridWidth = 1;
public static int halfGridWidth = gridWidth / 2;


public static int cellPadding = cellSize / 5;
public static int symbolSize = cellSize - cellPadding * 2;
public static int symbolStrokeWidth = 3;


public enum GameState {
JOUE,NUL,CERCLE_ROUGE_GAGNE,CERCLE_BLEU_GAGNE
}

private GameState actualState;


公共枚举令牌{
VIDE,CERCLE_ROUGE,CERCLE_BLEU
}

私有令牌actualPlayer;


私人令牌[] []板;
私人最终DrawCanvas画布;
私有JLabel statusBar;
私有JLabel indexIndicator;



public Pha(){

canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(canvasWidth,canvasHeight));


canvas.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
int x = e.getX( );
int y = e.getY();

int selectedRow = y / cellSize;
int selectedCol;
selectedCol = x / cellSize; $ b $ (actualState == GameState.JOUE){
if(selectedRow> = 0&& selectedRow< ROWS&&&selectedCol> = 0


b&& amp;& amp; amp; selectedCol< COLS&&
board [selectedRow] [selectedCol] == Token.VIDE){
board [selectedRow] [selectedCol] = actualPlayer;
actualiseJeu (actualPlayer,selectedRow,selectedCol);
actualPlayer =(actualPlayer == Token.CERCLE_BLEU)?Token.CERCLE_ROUGE:Token.CERCLE_BLEU;
}
} else {
initGame() ;
}

重绘();
}

});




statusBar = new JLabel();
statusBar.setFont(new Font(Font.DIALOG_INPUT,Font.ITALIC,15));
statusBar.setBorder(BorderFactory.createEmptyBorder(2,5,4,5));


容器cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas,BorderLayout.EAST);
cp.add(statusBar,BorderLayout.NORTH);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle(Pha par esQmo);
setVisible(true);

板=新令牌[ROWS] [COLS];
initGame();
}

public void initGame(){
(int intne = 0; ligne< ROWS; ++ ligne) ; colonne COLS; ++ colonne){
board [ligne] [colonne] = Token.VIDE;
}
}
actualState = GameState.JOUE;
actualPlayer = Token.CERCLE_ROUGE;
}

公共无效updateGame(令牌theSeed,INT ligneSelectionnee,INT colonneSelectionnee){
如果(aGagne(theSeed,ligneSelectionnee,colonneSelectionnee)){
actualState =( theSeed == Token.CERCLE_ROUGE)? GameState.CERCLE_ROUGE_GAGNE:GameState.CERCLE_BLEU_GAGNE;
} else if(estNul()){
actualState = GameState.CERCLE_BLEU_GAGNE;
}

}
public boolean estNul(){

return false;

$ b $(rowSelected,colSelected)* /
public boolean aGagne(Token theSeed,int ligneSelectionnee,int colonneSelectionnee){
return false;

/ *(普朗什[ligneSelectionnee] [colonneSelectionnee] == Jeton.CERCLE_BLEU
&安培;&安培;普朗什[ligneSelectionnee] [colonneSelectionnee - 1] == Jeton.CERCLE_BLEU
和;&安培;普朗什[ligneSelectionnee] [colonneSelectionnee + 1] == Jeton.CERCLE_BLEU
||普朗什[ligneSelectionnee - 1] [colonneSelectionnee] == Jeton.CERCLE_BLEU
&安培;&安培;普朗什[1] [ colneSelectionnee] == theSeed
&&& planche [2] [colonneSelectionnee] == theSeed
|| ligneSelectionnee == colonneSelectionnee
&&& planche [0] [0] == theSeed
&& planche [1] [1] == theSeed
&& planche [2] [2] == theSeed
|| ligneSelectionnee + colonneSelectionnee == 2
&& planche [0] [2] == theSeed
&& planche [1] [1] == theSeed
&& planche [2] [0] == theSeed); * /


}

class DrawCanvas extends JPanel {

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.WHITE);


g.setColor(Color.BLACK);
for(int ligne = 1; ligne< ROWS; ++ ligne){
g.fillRoundRect(0,cellSize * ligne - halfGridWidth,canvasWidth - 1,
gridWidth,gridWidth,gridWidth );
}
for(int colnene = 1; colnene COLS; ++ colnene){
g.fillRoundRect(cellSize * colnene - halfGridWidth,0 $ b $,gridWidth,canvasHeight - 1,
gridWidth,gridWidth);
}


Graphics2D g2d =(Graphics2D)g;
g2d.setStroke(new BasicStroke(symbolStrokeWidth,
BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND)); (int ligne = 0; ligne (intcolnene = 0; colnene< COLS; ++columnne){
int x1 = colne * cellSize + cellPadding;
int y1 = ligne * cellSize + cellPadding;

if(board [ligne] [colony] == Token.CERCLE_ROUGE){
g2d.setColor(Color.RED);
g2d.drawOval(x1,y1,symbolSize,symbolSize);
g2d.fillOval(x1,y1,symbolSize,symbolSize);
} else
if(board [ligne] [colony] == Token.CERCLE_BLEU){
int x2 = colonne * cellSize + cellPadding;
g2d.setColor(Color.BLUE);
g2d.drawOval(x1,y1,symbolSize,symbolSize);
g2d.fillOval(x2,y1,symbolSize,symbolSize); (actualState == GameState.JOUE){
if(actualPlayer == Token.CERCLE_ROUGE){
}
}

}

if {
statusBar.setText(ROUGE,c'est votre tour);
statusBar.setForeground(Color.RED);

} else {
statusBar.setText(BLEU,c'est votre tour);
statusBar.setForeground(Color.BLUE);
statusBar.addMouseMotionListener(null);
}
} else
if(actualState == GameState.NUL){
statusBar.setForeground(Color.yellow);
statusBar.setText(Match nul!Cliquez pour rejouer);
} else
if(actualState == GameState.CERCLE_ROUGE_GAGNE){
statusBar.setText(Le jouer X aremportéla partie,cliquez pour rejouer);
statusBar.setForeground(Color.RED);
} else
if(actualState == GameState.CERCLE_BLEU_GAGNE){
statusBar.setForeground(Color.BLUE);
statusBar.setText(Le joueur O aremportéla partie,cliquez pour rejouer);




$ b public static void main(String [] args){
SwingUtilities.invokeLater(() - > ; {
Pha pha = new Pha();
});
}
}


解决方案

这个

  // col,row:表示你想要找到的单元到
private void neighbors(int col ,int row){

//通过在col和row中添加+/- 1来查找所有serouding单元格(int colNum = col - 1; colNum< =(col + 1 ); colNum + = 1){

for(int rowNum = row-1; rowNum <=(row + 1); rowNum + = 1){

/ /(如果不是中心单元格)
if(!((colNum == col)&&(rowNum == row))){

//确保它位于网格
if(withinGrid(colNum,rowNum)){
System.out.println(Neighbor of+ col ++ row + - + colNum ++ rowNum);
}
}
}
}
}

//定义由colNum表示的单元格,rowNum在网格内
//(使用邻居的函数)
private boolean withinGrid(int colNum,int rowNum){

if((colNum <0)||(rowNum <0)){
返回false;如果行或列为负数,则返回false

if((colNum> = COLS)||(rowNum> = ROWS)){
return false; //如果行或列是>则为false> 75
}
返回true;
}

请不要犹豫,询问代码是否不清楚。

用你的代码来测试它,修改这个块:

pre $ if(actualState == GameState.JOUE) ((selectedRow> = 0)&& amp;(selectedRow< ROWS)&&& amp;(selectedCol> = 0)
&&(selectedCol< COLS)& ;&
(board [selectedRow] [selectedCol] == Token.VIDE)){
board [selectedRow] [selectedCol] = actualPlayer;
// actualiseJeu(actualPlayer,selectedRow,selectedCol);
actualPlayer =(actualPlayer == Token.CERCLE_BLEU)? Token.CERCLE_ROUGE:Token.CERCLE_BLEU;

//添加这个来调用函数:
neighbors(selectedCol,selectedRow);
}
}


I've a 2D grid of 75rows by 75 cols, I draw symbols of 2 colors (red and blue) on users clicks, it works fine but I'm stuck on a major problem I want to find the neighbor of those symbols: Example when the user click on a cell, it prints a symbol (oval) now I want that click also checks in its neighbors if the cell are occupied or empty, if occupied, by which symbol.

I found the algorithm below which seems to fit the need, but can't figure out how to adapt to my code:

private static int[][] array = new int[3][3];

    private static void initialiseArray() {
        int counter = 1;
        for (int row = ; row < 3; row++) {
            for (int col = ; col < 3; col++) {
                array[row][col] = counter;
                counter++;
            }
        }

    }

    public static void main(String args[]) {
        initialiseArray();
        for (int row = ; row < 3; row++) {
            for (int col = ; col < 3; col++) {
                System.out.print(array[row][col]);
                if( col == 2 ){
                    System.out.println("\n");
                }
            }
        }
        neighbours();
    }

    public static void neighbours(){  
        int posX = 2;
        int posY = 2;

        for( int row = posX - 1; row <= posX + 1; row++){
            for(int col =  posY -1;  col <= posY + 1; col++){
                if( !(posX == row &&  posY == col) && row >= && col >= && row < 3 && col < 3 ){
                    System.out.println(array[row][col]);
                }
            }
        }
    }

Below is my code, I need you help me solve this. Sorry bothering you.

public final class Pha extends JFrame {

    public static int ROWS = 75; 
    public static int COLS = 75;


    public static int cellSize = 15; 
    public static int canvasWidth = cellSize * COLS + (ROWS *4) ;
    public static int canvasHeight = cellSize * ROWS ;
    public static int gridWidth = 1;
    public static int halfGridWidth = gridWidth / 2;


    public static int cellPadding = cellSize / 5;
    public static int symbolSize = cellSize - cellPadding * 2; 
    public static int symbolStrokeWidth = 3; 


    public enum GameState{
        JOUE, NUL, CERCLE_ROUGE_GAGNE, CERCLE_BLEU_GAGNE
    }

    private GameState actualState;


    public enum Token{
        VIDE, CERCLE_ROUGE, CERCLE_BLEU
    }

    private Token actualPlayer; 


    private Token[][] board; 
    private final DrawCanvas canvas;
    private JLabel statusBar;
    private JLabel indexIndicator;



    public Pha(){

        canvas = new DrawCanvas(); 
        canvas.setPreferredSize(new Dimension(canvasWidth, canvasHeight));


        canvas.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();

        int selectedRow = y / cellSize;
        int selectedCol;
            selectedCol = x / cellSize;


        if(actualState == GameState.JOUE){
            if(selectedRow >= 0 && selectedRow < ROWS && selectedCol >= 0
                    && selectedCol < COLS &&
                    board[selectedRow][selectedCol] == Token.VIDE){
                board[selectedRow][selectedCol] = actualPlayer;
                actualiseJeu(actualPlayer, selectedRow, selectedCol); 
                actualPlayer = (actualPlayer == Token.CERCLE_BLEU)? Token.CERCLE_ROUGE : Token.CERCLE_BLEU;
            }
        } else { 
            initGame(); 
        }

        repaint(); 
    }

  });




    statusBar = new JLabel("  ");
    statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 15));
    statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));


    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(canvas, BorderLayout.EAST);
    cp.add(statusBar, BorderLayout.NORTH);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack(); 
    setTitle("Pha par esQmo");
    setVisible(true);

    board = new Token[ROWS][COLS];
    initGame();  
}

    public void initGame(){
        for(int ligne = 0; ligne < ROWS; ++ligne){
            for(int colonne = 0; colonne < COLS; ++colonne){
                board[ligne][colonne] = Token.VIDE;
            }
        }
        actualState = GameState.JOUE;
        actualPlayer = Token.CERCLE_ROUGE;
    }

    public void updateGame(Token theSeed, int ligneSelectionnee, int colonneSelectionnee) {
      if (aGagne(theSeed, ligneSelectionnee, colonneSelectionnee)) { 
         actualState= (theSeed == Token.CERCLE_ROUGE) ? GameState.CERCLE_ROUGE_GAGNE : GameState.CERCLE_BLEU_GAGNE;
      } else if (estNul()) {  
         actualState = GameState.CERCLE_BLEU_GAGNE;
      }

   }
 public boolean estNul() {

      return false; 
   }

       (rowSelected, colSelected) */
   public boolean aGagne(Token theSeed, int ligneSelectionnee, int colonneSelectionnee) {
      return false; 

      /* (planche[ligneSelectionnee][colonneSelectionnee] == Jeton.CERCLE_BLEU  
            && planche[ligneSelectionnee][colonneSelectionnee - 1] == Jeton.CERCLE_BLEU
            && planche[ligneSelectionnee][colonneSelectionnee + 1] == Jeton.CERCLE_BLEU
       || planche[ligneSelectionnee - 1][colonneSelectionnee] == Jeton.CERCLE_BLEU      
            && planche[1][colonneSelectionnee] == theSeed 
            && planche[2][colonneSelectionnee] == theSeed
       || ligneSelectionnee == colonneSelectionnee            
            && planche[0][0] == theSeed
            && planche[1][1] == theSeed
            && planche[2][2] == theSeed
       || ligneSelectionnee + colonneSelectionnee == 2 
            && planche[0][2] == theSeed
            && planche[1][1] == theSeed
            && planche[2][0] == theSeed);*/


}

class DrawCanvas extends JPanel{

        @Override
        public void paintComponent(Graphics g){ 
            super.paintComponent(g); 
            setBackground(Color.WHITE);


            g.setColor(Color.BLACK);
            for(int ligne = 1; ligne < ROWS; ++ligne){
                g.fillRoundRect(0, cellSize * ligne - halfGridWidth, canvasWidth - 1,
                        gridWidth, gridWidth, gridWidth);
            }
            for(int colonne = 1; colonne < COLS; ++colonne){
                g.fillRoundRect(cellSize * colonne - halfGridWidth, 0
                        , gridWidth, canvasHeight - 1,
                        gridWidth, gridWidth);
            }


            Graphics2D g2d = (Graphics2D)g;
            g2d.setStroke(new BasicStroke(symbolStrokeWidth,
                    BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); 
            for(int ligne = 0; ligne < ROWS; ++ligne){
                for(int colonne = 0; colonne < COLS; ++colonne){
                    int x1 = colonne * cellSize + cellPadding;
                    int y1 = ligne * cellSize + cellPadding;

                    if(board[ligne][colonne] == Token.CERCLE_ROUGE){
                        g2d.setColor(Color.RED);
                        g2d.drawOval(x1, y1, symbolSize, symbolSize);
                        g2d.fillOval(x1, y1, symbolSize, symbolSize);
                    } else
                        if(board[ligne][colonne] == Token.CERCLE_BLEU){
                            int x2 = colonne * cellSize + cellPadding;
                            g2d.setColor(Color.BLUE);
                            g2d.drawOval(x1, y1, symbolSize, symbolSize);
                            g2d.fillOval(x2, y1, symbolSize, symbolSize);
                        }
                }

            }

            if(actualState == GameState.JOUE){
                if(actualPlayer == Token.CERCLE_ROUGE){
                    statusBar.setText("ROUGE, c'est votre tour");
                    statusBar.setForeground(Color.RED);

                } else {
                    statusBar.setText("BLEU, c'est votre tour");
                    statusBar.setForeground(Color.BLUE);
                    statusBar.addMouseMotionListener(null);
                }
            } else
                if(actualState == GameState.NUL){
                    statusBar.setForeground(Color.yellow);
                    statusBar.setText("Match nul! Cliquez pour rejouer");
                } else
                    if(actualState == GameState.CERCLE_ROUGE_GAGNE){
                        statusBar.setText("Le jouer X a remporté la partie, cliquez pour rejouer");
                        statusBar.setForeground(Color.RED);
                    } else
                        if(actualState == GameState.CERCLE_BLEU_GAGNE){
                            statusBar.setForeground(Color.BLUE);
                            statusBar.setText("Le joueur O a remporté la partie, cliquez pour rejouer");
                        }
        }
    } 


    public static void main(String[] args){
        SwingUtilities.invokeLater(() -> {
            Pha pha = new Pha();
        });
    }
}

解决方案

Try this

//col , row : representing the cell you want to find neighbors to 
private void neighbours(int  col, int row) {

     //find all serouding cell by adding +/- 1 to col and row 
    for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1  ) {

        for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1  ) {

             //if not the center cell 
            if(! ((colNum == col) && (rowNum == row))) {

                //make sure it is within  grid
                if(withinGrid (colNum, rowNum)) {
                    System.out.println("Neighbor of "+ col+ " "+ row + " - " + colNum +" " + rowNum );
                }
            }
        }
    }
}

 //define if cell represented by colNum, rowNum is inside grid
//function used by neighbours()
private boolean withinGrid(int colNum, int rowNum) {

    if((colNum < 0) || (rowNum <0) ) {
        return false;    //false if row or col are negative
    }
    if((colNum >= COLS) || (rowNum >= ROWS)) {
        return false;    //false if row or col are > 75
    }
    return true;
}

Don't hesitate to ask if the code isn't clear.
To test it with you code modify this block:

    if(actualState == GameState.JOUE){
        if((selectedRow >= 0) && (selectedRow < ROWS) && (selectedCol >= 0)
                && (selectedCol < COLS) &&
                (board[selectedRow][selectedCol] == Token.VIDE)){
            board[selectedRow][selectedCol] = actualPlayer;
            //actualiseJeu(actualPlayer, selectedRow, selectedCol);
            actualPlayer = (actualPlayer == Token.CERCLE_BLEU)? Token.CERCLE_ROUGE : Token.CERCLE_BLEU;

            //add this to call function : 
            neighbours(selectedCol, selectedRow);
        }
    }

这篇关于寻找二维数组的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆