You need to enable JavaScript to run this app. Java使用DFS查找二维矩阵相同符号集群时win_clusters无输出问题
优惠活动
大模型
产品
解决方案
定价
更多

Java使用DFS查找二维矩阵相同符号集群时win_clusters无输出问题

问题排查与修复方案

核心问题清单

  • ROW、COLUMN未初始化:静态定义的测试grid是5行5列,但全局变量ROW、COLUMN默认值为0,DFS方法中的两层遍历条件i<ROW、j<COLUMN直接不生效,DFSUtil从未被调用,因此没有任何集群生成。
  • 全局Cluster对象逻辑错误:使用静态global_cluster存储集群数据,所有连通块的数据都会混入同一个对象,且遍历完单个连通块后没有重置操作,会导致数据覆盖、重复计数等问题。
  • 集群入库时机错误:当前将win_clusters.add(global_cluster)逻辑写在DFS递归的边界终止分支中,会导致同一个集群被重复添加多次,且无法正确统计完整连通块的大小。
  • 冗余变量未清理:静态变量cluster_length定义后从未使用,属于无效代码。

修复步骤

  1. 给ROW、COLUMN赋正确初始值,针对静态测试grid直接赋值为5即可,若使用随机生成矩阵则调用grid_creation方法自动赋值。
  2. 移除静态global_cluster变量,改为外层循环每次遇到未访问节点时,新建Cluster对象传入DFSUtil填充数据。
  3. 将集群大小判断逻辑移到DFSUtil调用结束后,完整统计完单个连通块的大小后再决定是否加入win_clusters。
  4. 清理无效的cluster_length变量。

修改后可运行代码

import java.util.*;
public class sample {

    static int grid[][]= {{1,3,0,4,0},
                          {3,2,0,0,1},
                          {0,4,1,0,1},
                          {4,0,0,0,2},
                          {2,4,0,2,4}};

    static int ROW = 5;
    static int COLUMN = 5;

    public static int[][] grid_creation(int numRows, int numCols){
        ROW= numRows;
        COLUMN=numCols;
        int [][]grid = new int[numRows][numCols];
        Random rand = new Random();
        for(int i = 0; i<numRows ; i++){
            for(int j = 0; j<numCols; j++){
                grid[i][j]= rand.nextInt(5);
            }
        }
        return grid;
    }

    public static void print_matrix(int[][]matrix){
        for(int i = 0; i< matrix.length;i++){
            for(int j = 0; j<matrix[0].length; j++){
                System.out.print(matrix[i][j]+" ");
            }
            System.out.println();
        }
    }

    public static boolean isValid(boolean[][] visited, int row, int col){
        if(row<0 ||col<0 || row>=ROW || col>=COLUMN || visited[row][col] )
            return false;

        return true;
    }

    public static class Cluster{
        List<Integer> cluster_symbol_positions = new ArrayList<Integer>();
        int symbol = -1;
        int count = 0;
        int win = 0;

        public void create_new_Cluster(){
            cluster_symbol_positions = new ArrayList<>();
            symbol = -1;
            count = 0;
            win= 0;
        }
        public List<Integer> get_cluster_symbol_positions(){
            return cluster_symbol_positions;
        }

        public int getSymbol(){return symbol;}
        public void setSymbol(int a){symbol = a;}
        public int getCount(){return count;}

        public  void add_to_cluster(int row1, int col1 ){
            int row = row1;
            int col = col1;
            cluster_symbol_positions.add(getReelPositionNumber(row,col));
            count++;
        }
        public  int cluster_win(Cluster cluster){
            int win_amount = 0;
            //return win amount from the paytable

            return win_amount;
        }
    }



    public static void DFS(int[][] grid,List<Cluster> win_clusters) {
        int h = grid.length;
        if (h == 0)
            return;
        int l = grid[0].length;

        //created visited array
        boolean [][] visited = new boolean[h][l];

        System.out.println("Depth-First Search: ");
        for( int i =0; i< ROW ; i++){
            for(int j = 0 ;j<COLUMN; j++){
                if(!visited[i][j]) {
                    Cluster currentCluster = new Cluster();
                    DFSUtil(grid, i, j, visited, currentCluster, grid[i][j]);
                    if(currentCluster.getCount() >=2){
                        win_clusters.add(currentCluster);
                    }
                }
            }
        }

    }

    public static void DFSUtil(int[][]grid, int row, int col, boolean[][] visited, Cluster currentCluster, int targetSymbol){

        if (row < 0 || col < 0 || row >= ROW|| col >= COLUMN || visited[row][col] || grid[row][col] != targetSymbol) {
            return;
        }

        visited[row][col] = true;
        currentCluster.add_to_cluster(row,col);
        currentCluster.setSymbol(targetSymbol);

        DFSUtil(grid, row+ 1, col,visited,currentCluster, targetSymbol); // go down
        DFSUtil(grid, row - 1, col, visited,currentCluster, targetSymbol); //go up
        DFSUtil(grid, row, col + 1,visited,currentCluster, targetSymbol); //go right
        DFSUtil(grid, row, col - 1,visited,currentCluster, targetSymbol); // go left
    }

    public static int getReelPositionNumber(int row, int col) {
        return (row*COLUMN) + col;
    }

    public static List<Integer> getReelPositionsIndex(int positionNumber) {

        List<Integer> tempData = new ArrayList<Integer>();
        int numReels =COLUMN;
        int display = ROW;
        if(positionNumber >= numReels*display)
            throw new RuntimeException( positionNumber+" is out of range "+ numReels*display +"(rows*cols) in the game." );
        if(positionNumber < numReels) {
            tempData.add(0);
            tempData.add(positionNumber);
        } else if(positionNumber == (numReels*display)) {
            tempData.add(display - 1);
            tempData.add(numReels - 1);
        } else {
            int row = positionNumber / numReels;
            int col = positionNumber % numReels;
            tempData.add(row);
            tempData.add(col);
        }
        return tempData;
    }

    public static void main(String args[]){
        System.out.println("Modified function for cluster win ");
        List<Cluster> win_clusters = new ArrayList<Cluster>();
        DFS(grid,win_clusters);
        print_matrix(grid);
        System.out.println("符合要求的集群数量:"+win_clusters.size());
        // 可遍历win_clusters打印详情
        for (int i = 0; i < win_clusters.size(); i++) {
            Cluster c = win_clusters.get(i);
            System.out.printf("集群%d:符号%d,大小%d,位置%s%n", i+1, c.getSymbol(), c.getCount(), c.get_cluster_symbol_positions());
        }
    }
}

运行结果说明

针对测试静态矩阵运行后,会输出符合大小≥2的集群数量,以及每个集群的符号、大小、包含的位置信息。

内容的提问来源于stack exchange,提问作者helloworld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 22:33:02