图形互补的这些代码片段有什么区别?

What is the difference between these code snippets of graph complementing?

本文关键字:片段 什么 区别 代码 图形      更新时间:2023-10-16

我使用这个代码片段来获取我的图的补码-

for(i = 1; i <= n; i++)
{
    for(j = 1; j <= n; j++)
    {
        if(i != j)
        {
            graph[i][j] = 1 - graph[i][j];
        }
    }
}

这给出了一个错误的答案。但是当我用下面的代码片段替换它时,它被接受了-

for(int i = 1; i <= n; i++){
   for(int j = 1; j <= n; j++){
        if(graph[i][j] == 1)
            graph[i][j] = 0;
        else if(i != j)
            graph[i][j] = 1;
    }
}

我看不出这两者有什么区别

this:

if(i!=j)
{
   graph[i][j]= 1-graph[i][j];
}

和下面的不一样:

if(graph[i][j] == 1)    graph[i][j] = 0;
else if(i != j)         graph[i][j] = 1;

在第一种情况下,你将矩阵修改为除了对角线以外的任何地方都是1-N

给定这个矩阵:

 1 1 0
 1 1 0 
 1 1 0

第一个代码会给你:

 1 0 0
 0 1 0 
 0 0 0

第二个会给你:

 0 0 1
 0 0 1 
 0 0 0

试试这个:

for(i = 1; i <= n; i++) {
    for(j = 1; j <= n; j++) {
        if(i != j || graph[i][j] == 1) {
            graph[i][j] = 1 - graph[i][j];
        }
    }
}

您只是没有添加代码graph[i][j] == 1