Interview Questions

226. In a nxn board, some nodes are black colored. Given a black node ......

Microsoft Interview Questions and Answers


(Continued from previous question...)

226. In a nxn board, some nodes are black colored. Given a black node ......

Question:
In a nxn board, some nodes are black colored. Given a black node, highlight all the black node connected to this given node directly or indirectly.


maybe an answer:


Say the element that is black colored is represented by 1, and others by 0. The following program will print out all the directly/indirectly connected black colored elemented for a specified element in the matrix. The idea is to if an element is black colored, then do the same check to all it's adjacent 8 nodes.

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

namespace HighLightBlackDotInMatrix
{
class Program
{
public static void HighLightDot(int[,] matrix, int x, int y)
{
Console.Write("({0},{1}) ", x, y);
matrix[x, y] = -1;
}
private static void DoHighLightBlackDotInMatrix(int[,] matrix, int x, int y, int n)
{
if (x < n &&&& x >= 0 && y < n &&&& y >= 0 &&&& matrix[x,y] == 1)
{

HighLightDot(matrix, x, y);
DoHighLightBlackDotInMatrix(matrix, x-1, y-1, n);
DoHighLightBlackDotInMatrix(matrix, x-1, y, n);
DoHighLightBlackDotInMatrix(matrix, x-1, y+1, n);
DoHighLightBlackDotInMatrix(matrix, x, y-1, n);
DoHighLightBlackDotInMatrix(matrix, x, y+1, n);
DoHighLightBlackDotInMatrix(matrix, x+1, y-1, n);
DoHighLightBlackDotInMatrix(matrix, x+1, y, n);
DoHighLightBlackDotInMatrix(matrix, x+1, y+1, n);
}
}
static void HighLightBlackDotInMatrix(int[,] matrix, int x, int y, int n)
{
DoHighLightBlackDotInMatrix(matrix, x, y, n);
Console.WriteLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i, j] == -1)
{
matrix[i, j] = 1;
}
}
}
}

static void PrintMatrix(int[,] matrix, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write("{0} ", matrix[i,j]);
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
int[,] matrix = new [,] {{1,0,0,1,0}, {1,0,1,0,1}, {0,1,1,1,0}, {0,0,0,0,0}, {1,1,1,1,1}};
Console.WriteLine("Array Dimension:{0} x {1}", matrix.Length, matrix.LongLength);
PrintMatrix(matrix, 5);
HighLightBlackDotInMatrix(matrix, 0,0, 5);
PrintMatrix(matrix, 5);
}
}
}

(Continued on next question...)

Other Interview Questions