Advertisement
Guest User

DepthFirstSearch

a guest
Jan 26th, 2014
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. using System;
  2. class DepthFirstSearch
  3. {
  4.     static void Main()
  5.     {
  6.         int[,] m = { { 1, 3, 2, 2, 2, 4 }, { 3, 3, 3, 2, 4, 4 }, { 4, 3, 1, 2, 3, 3 }, { 4, 3, 1, 3, 3, 1 } };
  7.         int maxPath = 0;
  8.         for (int r = 0; r < m.GetLength(0); r++)
  9.             for (int c = 0; c < m.GetLength(1); c++)
  10.             {
  11.                 int count = 1;
  12.                 FindPath(m, m[r, c], new bool[m.GetLength(0), m.GetLength(1)], r, c, ref count);
  13.                 if (count > maxPath) maxPath = count;
  14.             }
  15.         Console.WriteLine(maxPath);
  16.     }
  17.     private static void FindPath(int[,] m, int n, bool[,] tM, int r, int c, ref int count)
  18.     {
  19.         tM[r, c] = true;
  20.         if (r > 0 && !tM[r - 1, c] && m[r - 1, c] == n) count = Count(m, n, tM, count, r - 1, c);
  21.         if (r < m.GetLength(0) - 1 && !tM[r + 1, c] && m[r + 1, c] == n) count = Count(m, n, tM, count, r + 1, c);
  22.         if (c > 0 && !tM[r, c - 1] && m[r, c - 1] == n) count = Count(m, n, tM, count, r, c - 1);
  23.         if (c < m.GetLength(1) - 1 && !tM[r, c + 1] && m[r, c + 1] == n) count = Count(m, n, tM, count, r, c + 1);
  24.     }
  25.     private static int Count(int[,] m, int n, bool[,] tM, int count, int nr, int nc)
  26.     {
  27.         tM[nr, nc] = true;
  28.         count++;
  29.         FindPath(m, n, tM, nr, nc, ref count);
  30.         return count;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement