2012-10-07 87 views
1

我有一个二维数组int matrix [numNodes] [numArcs]。这是一个关联矩阵。java在二维矩阵中移动

现在,如果我们想添加一个弧,我们必须检查那些存在的节点并且弧不存在。这部分运作良好。我需要做的以下事情是找到一个空列来添加弧线。所以矩阵在开始处充满了零。所以很简单,你搜索每一列,直到你找到一个满了零的列。听起来很简单,但现在工作。在这部分代码如下:

outerloop: 
    for (int i = 0; i < numArcs; i++){ 
     for (int j = 0; j < numNodes; j++){ 
      if (matriz[j][i] != 0) 
       break; 
       //It finds a number != 0 so it should move to the next column 

      //If it gets here, the whole column was full of zeros 
      column = i; 
      key = true; 
      break outerloop; 
     } 
    } 

我用钥匙知道我找到列,因为如果我不它,因为矩阵是充分,我需要复制它。那是另一个与这个问题无关的问题。现在

,我试图找出问题,我注意到以下几点:它只是检查这些位置:

01 
02 
03 
03 

正如你所看到的,它只是检查各列的第一位置,并不会全部它的方式应该如何。对我来说这没有意义。在我的例子中NumNode是10,所以它应该一直下降。

编辑: 我确切的例子 矩阵是这样的:

-1 -1 -1 0 0 0 .... 
    0 1 0 0 0 ... 
    0 0 1 0 0 ..... 

因此,当它到达第四栏时,它读取的是零和返回这就是空列。 它对于我添加的下一个n弧线也是一样的。我添加的以下弧线不再接触第一行。 感谢您的帮助

+0

是你的'matriz'变量的类型'double [] []'有没有机会? –

+0

没有它的int [] [] – Alessandroempire

回答

1
for (int i = 0; i < numArcs; i++){ 
    for (int j = 0; j < numNodes; j++){ 
     if (matriz[j][i] != 0) 
      break; 
      //It finds a number != 0 so it should move to the next column 

     //If it gets here, the whole column was full of zeros 
     column = i; 
     key = true; 
     break outerloop; 
    } 
} 

如果在内部循环,你不会是第一次打破..你会i存入列,不检查其他行该列..

你可以更好地使用布尔标志变量来检查你想要的东西。

int[][] matrix = new int[5][4]; 
    boolean columnEmpty = true; 
    int column = 0; 
    boolean key = false; 

    matrix[0][0] = -1; 
    matrix[0][1] = -1; 
    matrix[1][1] = 1; 
    matrix[1][2] = -1; 
    matrix[2][2] = -1; 

    outerloop: for (int i = 0; i < 5; i++){ 
      columnEmpty = true; 
      for (int j = 0; j < 4; j++){ 
       if (matrix[j][i] != 0) { 
        columnEmpty = false; 
        break; 
       } 

      } 
      if (columnEmpty) { 
       // If we are here.. then flag was never set to `true`. 
       // So, all the rows for that column was Zero.. 
       column = i; 
       key = true; 
       break outerloop; 
      } 

     } 

    System.out.println("Column : " + column); 
+0

让我试试看,并让你知道在几个 – Alessandroempire

+0

而不是使用'break',你甚至可以检查循环条件:'boolean colEmpty = true; for(int j = 0; j

+0

@YanickRochon .. Yeah that can be done ..但是,性能不会有太大的区别..仍然是一个有效的解决方案.. –