Binary Matrix Transformation

Given a binary matrix, modify it such that if a cell (i, j) contains 0 then make all the cells of ith row and jth column as 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] matrix = {
                                { 1, 1, 1 },
                                { 1, 0, 1 },
                                { 1, 1, 1 }
                            };

            ArrayList rowList = new ArrayList();
            ArrayList colList = new ArrayList();

            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    if (matrix[i, j] == 0)
                    {
                        if(!rowList.Contains(i))
                        {
                            rowList.Add(i);
                        }
                        if (!colList.Contains(j))
                        {
                            colList.Add(j);
                        }
                    }
                }
            }
            
            for (int i = 0; i < rowList.Count; i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    matrix[(int)rowList[i], j] = 0;
                }
            }

            for (int j = 0; j < colList.Count; j++)
            {
                for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    matrix[i, (int)colList[j]] = 0;
                }
            }

            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

Output
=======
1 0 1
0 0 0
1 0 1
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s