Advertisement
AmidamaruZXC

Untitled

Oct 16th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Task4
  4. {
  5.     class Program
  6.     {
  7.         private static bool dfs(int i, int j, int[,] g)
  8.         {
  9.             if (i < 0 || i >= g.GetLength(0) || j < 0 || j >= g.GetLength(0) || g[i, j] == 0)
  10.                 return false;
  11.             g[i, j] = 0;
  12.             dfs(i - 1, j, g);
  13.             dfs(i + 1, j, g);
  14.             dfs(i, j - 1, g);
  15.             dfs(i, j + 1, g);
  16.             return true;
  17.         }
  18.         private static int numIslands(int[,] grid)
  19.         {
  20.             int[,] g = grid;
  21.             int n = grid.GetLength(0);
  22.             if (n == 0)
  23.                 return 0;
  24.             int m = grid.GetLength(1);
  25.             if (m == 0)
  26.                 return 0;
  27.             int count = 0;
  28.             for (int i = 0; i < n; ++i)
  29.                 for (int j = 0; j < m; ++j)
  30.                     if (dfs(i, j, g))
  31.                         ++count;
  32.             return count;
  33.         }
  34.  
  35.         static void Main(string[] args)
  36.         {
  37.             string input = Console.In.ReadToEnd();
  38.             string[] strings = input.Split('\n');
  39.             char[] MyChar = { '\r', ']', '[', ' ' };
  40.             int n = strings.Length - 3;
  41.             int m = strings[1].Split(',').Length - 1;
  42.             int[,] matrix = new int[n, m];
  43.             for (int i = 1; i < strings.Length - 2; ++i)
  44.             {
  45.                 string[] str = strings[i].Split(',');
  46.                 str[0] = str[0].TrimStart(MyChar);
  47.                 str[str.Length - 2] = str[str.Length - 2].TrimEnd(MyChar);
  48.                 for (int j = 0; j < str.Length - 1; ++j)
  49.                     matrix[i - 1, j] = int.Parse(str[j]);
  50.             }
  51.             Console.WriteLine(numIslands(matrix));
  52.             //for (int i = 0; i < n; i++)
  53.             //{
  54.             //    for (int j = 0; j < m; j++)
  55.             //        Console.Write($"{matrix[i, j]} ");
  56.             //    Console.WriteLine();
  57.             //}
  58.         }
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement