zoukankan      html  css  js  c++  java
  • CCI_Q1.7

    本文参考该作者文章当作编程笔记:
    
    作者:Hawstein
    出处:http://hawstein.com/posts/ctci-solutions-contents.html

    一.

    Q:写一个函数处理一个N×M的矩阵,如果矩阵中某个元素为0,那么把它所在的行和列都置为0.

    思路:额外申请两个数组row[N],col[M],如果元素s[i][j]等于0,那么row[i]和col[j]都等于0,最后重新遍历数组,将行列对应的元素设为0.

    CODE:

     1 #include<stdio.h>
     2 #include<memory.h>
     3 #define N 4
     4 #define M 4
     5 void zero(int s[][M] )
     6 {
     7     int row[N],col[M],i,j;
     8     memset(row,0,sizeof(row));
     9     memset(col,0,sizeof(col));
    10     for(i=0;i<N;i++)
    11         for(j=0;j<M;j++)
    12         {
    13             if(s[i][j]==0)
    14             {
    15                 row[i]=1;
    16                 col[j]=1;
    17             }
    18         }
    19     for(i=0;i<N;i++)
    20         for(j=0;j<M;j++)
    21         {
    22             if(row[i]==1||col[j]==1)
    23                 s[i][j]=0;
    24         }
    25 
    26 }
    27 int main(void)
    28 {
    29     int s[N][M]={{1,2,3,0},{6,2,3,6},{9,8,8,4},{1,0,2,3}};
    30     int i,j;
    31     for(i=0;i<N;i++)
    32     {
    33         for(j=0;j<M;j++)
    34             printf("%4d",s[i][j]);
    35         printf("
    ");
    36     }
    37     printf("
    ");
    38     zero(s);
    39     for(i=0;i<N;i++)
    40     {
    41         for(j=0;j<M;j++)
    42             printf("%4d",s[i][j]);
    43         printf("
    ");
    44     }
    45 
    46     return 0;
    47 }
  • 相关阅读:
    blocksit
    getdata
    ASP.net 探针
    301重定向
    webapi
    Unity NGUI UIPanel下对粒子的剪裁
    unity3d 之本地推送
    c#之时间戳与DateTime的相互转换
    c#之从服务器下载压缩包,并解压
    Unity3d 开发之 ulua 坑的总结
  • 原文地址:https://www.cnblogs.com/jhooon/p/3576973.html
Copyright © 2011-2022 走看看