// C# program to find minimum initial
// vertices to reach whole matrix.
using System;
using System.Collections.Generic;
class GFG {
static readonly int MAX = 100;
// (n, m) is current source cell from which
// we need to do DFS. N and M are total no.
// of rows and columns.
static void dfs(int n, int m, bool[, ] visit,
int[, ] adj, int N, int M)
{
// Marking the vertex as visited
visit[n, m] = true;
// If below neighbor is valid and has
// value less than or equal to current
// cell's value
if (n + 1 < N && adj[n, m] >= adj[n + 1, m]
&& !visit[n + 1, m])
dfs(n + 1, m, visit, adj, N, M);
// If right neighbor is valid and has
// value less than or equal to current
// cell's value
if (m + 1 < M && adj[n, m] >= adj[n, m + 1]
&& !visit[n, m + 1])
dfs(n, m + 1, visit, adj, N, M);
// If above neighbor is valid and has
// value less than or equal to current
// cell's value
if (n - 1 >= 0 && adj[n, m] >= adj[n - 1, m]
&& !visit[n - 1, m])
dfs(n - 1, m, visit, adj, N, M);
// If left neighbor is valid and has
// value less than or equal to current
// cell's value
if (m - 1 >= 0 && adj[n, m] >= adj[n, m - 1]
&& !visit[n, m - 1])
dfs(n, m - 1, visit, adj, N, M);
}
static void printMinSources(int[, ] adj, int N, int M)
{
// Storing the cell value and cell indices
// in a list.
List<Tuple<int, Tuple<int, int> > > x
= new List<Tuple<int, Tuple<int, int> > >();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
x.Add(Tuple.Create(adj[i, j],
Tuple.Create(i, j)));
}
}
// Sorting the newly created array according
// to cell values
x.Sort();
// Create a visited array for DFS and
// initialize it as false.
bool[, ] visit = new bool[N, MAX];
for (int i = 0; i < N; i++) {
for (int j = 0; j < MAX; j++)
visit[i, j] = false;
}
// Applying dfs for each vertex with
// highest value
for (int i = x.Count - 1; i >= 0; i--) {
// If the given vertex is not visited
// then include it in the set
if (!visit[x[i].Item2.Item1,
x[i].Item2.Item2]) {
Console.WriteLine("{0} {1}",
x[i].Item2.Item1,
x[i].Item2.Item2);
dfs(x[i].Item2.Item1, x[i].Item2.Item2,
visit, adj, N, M);
}
}
}
static void Main(string[] args)
{
int N = 2, M = 2;
int[, ] adj = { { 3, 3 }, { 1, 1 } };
printMinSources(adj, N, M);
}
}
// This code is contributed by cavi4762.