计算Matrix Java

时间:2016-11-03 02:00:48

标签: java recursion matrix

问题是在2d矩阵中计算连接的“@”的数量。我一直收到堆栈溢出错误,不知道为什么。构造函数将随机将@s和-s加载到矩阵中。获取提供的行和列位置,并计算有多少@符号连接到原始位置。如果@符号相互连接起来,向下,向左和向右连接,则会连接它们。

这是我的代码:

public class AtCounter{
private String[][] atMat = {   {"@","-","-","-","-"},
                              {"@","@","@","-","-"},
                              {"-","-","@","-","-"},
                              {"-","-","@","@","-"},
                              {"-","-","-","-","-"}
                            };
private boolean[][] visited;
private int totalCount = 0;
public AtCounter(int size)
{
    //size the matrix
    //use nested loops to randomly load the matrix, will do once i get the recursion down
    /*for(int i = 0; i < size; i++){
        for(int j = 0; j < size; j++){
            int number = (int)(Math.random() * 10) + 1;
            if(number % 2 == 0){
                atMat[i][j] = "@";
            }else{
                atMat[i][j] = "-";
            }
        }
    }*/
            visited = new boolean[atMat.length][atMat.length];
}
    public boolean inBounds(int r, int c){
        return ((r > -1 && r < atMat.length) && (c > -1 && c < atMat.length));
    }
public int countAts(int r, int c)
{
    //add in recursive code to count up the # of @s connected
    //start checking at spot [r,c]
            if(atMat[r][c].equals("-") || !inBounds(r,c)){
               return 0;
            }
            if(!visited[r][c]){
                if(atMat[r][c].equals("@")){
                    totalCount+=1;
                    //up
                    if(inBounds(r - 1, c)){
                        countAts(r - 1, c);
                    }
                    //down
                    if(inBounds(r + 1, c)){
                        countAts(r + 1, c);
                    }
                    //right
                    if(inBounds(r, c + 1)){
                        countAts(r , c + 1);
                    }
                    //left
                    if(inBounds(r, c  - 1)){
                        countAts(r, c - 1);
                    }
                }
            }
            return totalCount;        
     }
}

0 个答案:

没有答案