# Min number of moves to traverse entire Matrix through connected cells with equal values

Given a matrix A[][] of dimensions N*M, the task is to find the minimum number of moves required to traverse the entire matrix starting from (0, 0) by traversing connected cells with equal values at every step.

From a cell (i, j), cells (i + 1, j), (i – 1, j), (i, j – 1) and (i, j + 1) can be connected.

Examples:

Input: arr[][] = {{1, 1, 2, 2, 1}, {1, 1, 2, 2, 1}, {1, 1, 1, 3, 2}}
Output:
Explanation:
Minimum 5 moves are required to traverse the matrix.
First move: Starting from [0, 0], traverse cells [0, 1], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2] as all these cells have same value 1.
Second move: Traverse cells [0, 2], [0, 3], [1, 3], [1, 2] as all these cells have value 2.
Third move: Traverse cells [0, 4], [1, 4] containing 1.
Fourth move: Traverse [2, 3] containing 3.
Fifth move: Traverse [2, 4] containing 4.

Input: arr[][] = {{2, 1, 3}, {1, 1, 2}}
Output:
Explanation:
Minimum 4 moves are required to cover this 2-D array
First move: Traverse only [0, 0] as no other connected cell has value 2.
Second move: Traverse cells [0, 1], [1, 1], [1, 0] as these cells contain value 1.
Third move: Traverse cell [0, 2] containing 3.
Fourth move: Traverse cell [1, 2] containing 2.

Approach:
Follow the steps below to solve the problem:

• Create another matrix fill each cell with distinct values.
• Traverse matrix A[][] starting from (0, 0). For every cell (i, j), check if its adjacent cells have same value as A[i][j] or not.
• If any adjacent cell has same value, replace that cell in B[][] with the value of B[i][j].
• Count of remaining distinct elements in the B[][] matrix after completing the traversal of A[][], gives the required answer.

Below is the implementation of the above approach:

 `// C++ program to find the` `// minimum number of moves` `// to traverse a given matrix`   `#include ` `using` `namespace` `std;`   `// Function to find the minimum` `// number of moves to traverse` `// the given matrix` `int` `solve(``int` `A[][10], ``int` `N, ``int` `M)` `{`   `    ``int` `B[N][M];` `    ``int` `c = 1;` `    ``set<``int``> s;`   `    ``// Constructing another matrix` `    ``// consisting of distinct values` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``for` `(``int` `j = 0; j < M; j++)` `            ``B[i][j] = c++;` `    ``}`   `    ``// Updating the array B by checking` `    ``// the values of A that if there are` `    ``// same values connected` `    ``// through an edge or not` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``for` `(``int` `j = 0; j < M; j++) {`   `            ``// Check for boundary` `            ``// condition of the matrix` `            ``if` `(i != 0) {`   `                ``// If adjacent cells have` `                ``// same value` `                ``if` `(A[i - 1][j] == A[i][j])` `                    ``B[i - 1][j] = B[i][j];` `            ``}`   `            ``// Check for boundary` `            ``// condition of the matrix` `            ``if` `(i != N - 1) {`   `                ``// If adjacent cells have` `                ``// same value` `                ``if` `(A[i + 1][j] == A[i][j])` `                    ``B[i + 1][j] = B[i][j];` `            ``}`   `            ``// Check for boundary` `            ``// condition of the matrix` `            ``if` `(j != 0) {`   `                ``// If adjacent cells have` `                ``// same value` `                ``if` `(A[i][j - 1] == A[i][j])` `                    ``B[i][j - 1] = B[i][j];` `            ``}`   `            ``// Check for boundary` `            ``// condition of the matrix` `            ``if` `(j != M - 1) {`   `                ``// If adjacent cells have` `                ``// same value` `                ``if` `(A[i][j + 1] == A[i][j])` `                    ``B[i][j + 1] = B[i][j];` `            ``}` `        ``}` `    ``}`   `    ``// Store all distinct elements` `    ``// in a set` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``for` `(``int` `j = 0; j < M; j++)` `            ``s.insert(B[i][j]);` `    ``}`   `    ``// Return answer` `    ``return` `s.size();` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `N = 2, M = 3;` `    ``int` `A[][10] = { { 2, 1, 3 },` `                    ``{ 1, 1, 2 } };` `    ``// Function Call` `    ``cout << solve(A, N, M);` `}`

 `// Java program to find the` `// minimum number of moves` `// to traverse a given matrix` `import` `java.util.*;`   `class` `GFG{`   `// Function to find the minimum` `// number of moves to traverse` `// the given matrix` `static` `int` `solve(``int` `A[][], ``int` `N, ` `                            ``int` `M)` `{` `    ``int` `[][]B = ``new` `int``[N][M];` `    ``int` `c = ``1``;` `    `  `    ``HashSet s = ``new` `HashSet();`   `    ``// Constructing another matrix` `    ``// consisting of distinct values` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `       ``for``(``int` `j = ``0``; j < M; j++)` `          ``B[i][j] = c++;` `    ``}`   `    ``// Updating the array B by checking` `    ``// the values of A that if there are` `    ``// same values connected` `    ``// through an edge or not` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{` `       ``for``(``int` `j = ``0``; j < M; j++)` `       ``{` `           `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(i != ``0``)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i - ``1``][j] == A[i][j])` `                  ``B[i - ``1``][j] = B[i][j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(i != N - ``1``)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i + ``1``][j] == A[i][j])` `                  ``B[i + ``1``][j] = B[i][j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(j != ``0``)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i][j - ``1``] == A[i][j])` `                  ``B[i][j - ``1``] = B[i][j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(j != M - ``1``)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i][j + ``1``] == A[i][j])` `                  ``B[i][j + ``1``] = B[i][j];` `          ``}` `       ``}` `    ``}`   `    ``// Store all distinct elements` `    ``// in a set` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{` `       ``for``(``int` `j = ``0``; j < M; j++)` `          ``s.add(B[i][j]);` `    ``}`   `    ``// Return answer` `    ``return` `s.size();` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `N = ``2``, M = ``3``;` `    ``int` `A[][] = { { ``2``, ``1``, ``3` `},` `                  ``{ ``1``, ``1``, ``2` `} };` `                  `  `    ``// Function Call` `    ``System.out.print(solve(A, N, M));` `}` `}`   `// This code is contributed by 29AjayKumar`

 `# Python3 program to find the ` `# minimum number of moves ` `# to traverse a given matrix `   `# Function to find the minimum ` `# number of moves to traverse ` `# the given matrix ` `def` `solve(A, N, M): ` `  `  `    ``B ``=` `[] ` `    ``c ``=` `1` `    ``s ``=` `set``() ` `    `  `    ``# Constructing another matrix ` `    ``# consisting of distinct values ` `    ``for` `i ``in` `range``(N): ` `        ``new ``=` `[] ` `        ``for` `j ``in` `range``(M):` `            ``new.append(c)` `            ``c ``=` `c ``+` `1` `            `  `        ``B.append(new)`   `    ``# Updating the array B by checking ` `    ``# the values of A that if there are ` `    ``# same values connected ` `    ``# through an edge or not ` `    ``for` `i ``in` `range``(N): ` `        ``for` `j ``in` `range``(M):` `  `  `            ``# Check for boundary ` `            ``# condition of the matrix ` `            ``if` `i !``=` `0``: ` `  `  `                ``# If adjacent cells have ` `                ``# same value ` `                ``if` `A[i ``-` `1``][j] ``=``=` `A[i][j]: ` `                    ``B[i ``-` `1``][j] ``=` `B[i][j] ` `  `  `            ``# Check for boundary ` `            ``# condition of the matrix ` `            ``if` `(i !``=` `N ``-` `1``): ` `  `  `                ``# If adjacent cells have ` `                ``# same value ` `                ``if` `A[i ``+` `1``][j] ``=``=` `A[i][j]:` `                    ``B[i ``+` `1``][j] ``=` `B[i][j]` `  `  `            ``# Check for boundary ` `            ``# condition of the matrix ` `            ``if` `(j !``=` `0``): ` `  `  `                ``# If adjacent cells have ` `                ``# same value ` `                ``if` `A[i][j ``-` `1``] ``=``=` `A[i][j]: ` `                    ``B[i][j ``-` `1``] ``=` `B[i][j]` `  `  `            ``# Check for boundary ` `            ``# condition of the matrix ` `            ``if` `(j !``=` `M ``-` `1``): ` `  `  `                ``# If adjacent cells have ` `                ``# same value ` `                ``if` `(A[i][j ``+` `1``] ``=``=` `A[i][j]):  ` `                    ``B[i][j ``+` `1``] ``=` `B[i][j]` `  `  `    ``# Store all distinct elements ` `    ``# in a set ` `    ``for` `i ``in` `range``(N): ` `        ``for` `j ``in` `range``(M):` `            ``s.add(B[i][j]) ` `            `  `    ``# Return answer ` `    ``return` `len``(s)`   `# Driver code` `N ``=` `2` `M ``=` `3` `A ``=` `[ [ ``2``, ``1``, ``3` `], [ ``1``, ``1``, ``2` `] ] `   `# Function call ` `print``(solve(A, N, M)) `   `# This code is contributed by divyeshrabadiya07`

 `// C# program to find the` `// minimum number of moves` `// to traverse a given matrix` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG{`   `// Function to find the minimum` `// number of moves to traverse` `// the given matrix` `static` `int` `solve(``int` `[,]A, ``int` `N, ` `                           ``int` `M)` `{` `    ``int` `[,]B = ``new` `int``[N, M];` `    ``int` `c = 1;` `    `  `    ``HashSet<``int``> s = ``new` `HashSet<``int``>();`   `    ``// Constructing another matrix` `    ``// consisting of distinct values` `    ``for``(``int` `i = 0; i < N; i++)` `    ``{` `       ``for``(``int` `j = 0; j < M; j++)` `          ``B[i, j] = c++;` `    ``}`   `    ``// Updating the array B by checking` `    ``// the values of A that if there are` `    ``// same values connected` `    ``// through an edge or not` `    ``for``(``int` `i = 0; i < N; i++) ` `    ``{` `       ``for``(``int` `j = 0; j < M; j++)` `       ``{` `           `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(i != 0)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i - 1, j] == A[i, j])` `                  ``B[i - 1, j] = B[i, j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(i != N - 1)` `          ``{`   `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i + 1, j] == A[i, j])` `                  ``B[i + 1, j] = B[i, j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(j != 0)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i, j - 1] == A[i, j])` `                  ``B[i, j - 1] = B[i, j];` `          ``}` `          `  `          ``// Check for boundary` `          ``// condition of the matrix` `          ``if` `(j != M - 1)` `          ``{` `              `  `              ``// If adjacent cells have` `              ``// same value` `              ``if` `(A[i, j + 1] == A[i, j])` `                  ``B[i, j + 1] = B[i, j];` `          ``}` `       ``}` `    ``}`   `    ``// Store all distinct elements` `    ``// in a set` `    ``for``(``int` `i = 0; i < N; i++) ` `    ``{` `       ``for``(``int` `j = 0; j < M; j++)` `          ``s.Add(B[i, j]);` `    ``}`   `    ``// Return answer` `    ``return` `s.Count;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `    ``int` `N = 2, M = 3;` `    ``int` `[,]A = { { 2, 1, 3 },` `                 ``{ 1, 1, 2 } };` `                    `  `    ``// Function Call` `    ``Console.Write(solve(A, N, M));` `}` `}`   `// This code is contributed by 29AjayKumar`

Output:
```4

```

Time Complexity: O(N2
Auxiliary Space: O(N2)

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :