矩阵置零

    题意是要求在01矩阵中,把0的点的行和列都置零。

#include <iostream>
#include <vector>
#include <utility>
 
using namespace std;
 
void unguarded_setZero(int *matrix, int m, int n, int i, int j)
{
    for (int ii = 0; ii < m; ++ii)
    {
        *(matrix + ii * n + j) = 0;
    }
 
    for (int jj = 0; jj < n; ++jj)
    {
        *(matrix + i * n + jj) = 0;
    }
}
 
void solve(int *matrix, int m, int n)
{
    if (matrix == NULL || m <= 0 || n <= 0)
    {
        return;
    }
 
    vector<pair<int, int> > vecZero;
 
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            if (*(matrix + i * n  + j) == 0)
            {
                vecZero.push_back(make_pair(i, j));
            }
        }
    }
 
    for (vector<pair<int, int> >::const_iterator it = vecZero.begin();
        it != vecZero.end();
        ++it)
    {
        const int i = it->first;
        const int j = it->second;
 
        unguarded_setZero(matrix, m, n, i, j);
    }
}
 
int main(int argc, char **argv)
{
    int matrix[][6] =
    {
        {1, 1, 0, 1, 1, 1},
        {0, 1, 1, 1, 0, 1},
        {1, 1, 1, 1, 1, 1}
    };
 
    solve((int *)matrix, 3, 6);
 
    for (size_t i = 0; i < sizeof(matrix) / sizeof(*matrix); ++i)
    {
        for (size_t j = 0; j < sizeof(*matrix) / sizeof(**matrix); ++j)
        {
            cout << matrix[i][j] << " ";
        }
 
        cout << endl;
    }
}
posted @ 2012-10-01 12:06  紫红的泪  阅读(413)  评论(0编辑  收藏  举报