Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Numerics;
- int[,] matrix = {
- { 1, 0, 0, 0, 0, 0 },
- { 0, 1, 0, 1, 1, 1 },
- { 0, 0, 1, 0, 1, 0 },
- { 1, 1, 0, 0, 1, 0 },
- { 1, 0, 1, 1, 0, 0 },
- { 1, 0, 0, 0, 0, 1 },
- };
- void Print(int[,] matrix)
- {
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- for (int j = 0; j < matrix.GetLength(1); j++)
- {
- Console.Write(matrix[i, j] + ",");
- }
- Console.WriteLine();
- }
- }
- // b
- var linkBorder = new bool[matrix.GetLength(0), matrix.GetLength(1)];
- // todo: explore this
- // var m = new Matrix3x2();
- static void RemoveIslands(int[,] matrix, bool[,] borderLink)
- {
- // int[,] directions = {
- // { 0, -1 }, // left
- // { 0, 1 }, // right
- // { 1, 0 }, // down
- // { -1, 0 }, // up
- // };
- (int, int)[] directions = {
- (0, -1), // left
- (0, 1), // right
- (1, 0), // down
- (-1, 0), // up
- };
- var rowCount = matrix.GetLength(0);
- var colCount = matrix.GetLength(1);
- for (int r = 0; r < rowCount; r++)
- {
- for (int c = 0; c < colCount; c++)
- {
- if (matrix[r, c] == 1 && IsOneBorderAdjacent(r, c, rowCount, colCount) == borderLink[r, c] == false)
- {
- borderLink[r, c] = true;
- CheckNeighbors(r, c);
- }
- }
- }
- for (int i = 0; i < borderLink.GetLength(0); i++)
- {
- for (int j = 0; j < borderLink.GetLength(1); j++)
- {
- if (borderLink[i, j] == false)
- {
- matrix[i, j] = 0;
- }
- }
- }
- void CheckNeighbors(int r, int c)
- {
- foreach ((int row, int col) direction in directions)
- {
- int nextRow = r + direction.row;
- int nextCol = c + direction.col;
- // invalid direction
- if (!IsWithinPerimeter(nextRow, nextCol, rowCount, colCount) || matrix[nextRow, nextCol] != 1)
- {
- continue;
- }
- if (matrix[nextRow, nextCol] == 1 && borderLink[nextRow, nextCol] == false)
- {
- borderLink[nextRow, nextCol] = true;
- CheckNeighbors(nextRow, nextCol);
- }
- }
- }
- }
- // for a fized
- static bool IsOneBorderAdjacent(int row, int col, int rowCount, int colCount)
- {
- if (!IsWithinPerimeter(row, col, rowCount, colCount)) return false;
- return (row == 0 || row + 1 == rowCount || col + 1 == colCount);
- }
- // validates if the coords are within bound to not go outside of perimeter of the matrix
- static bool IsWithinPerimeter(int row, int col, int rowCount, int colCount)
- {
- return row >= 0 && row < rowCount && col >= 0 && col < colCount;
- }
- static void Analyzes(int[,] matrix)
- {
- foreach (int value in new[,] { { 1, 2 }, { 3, 4 } })
- {
- // output: 1,2,3,4
- Console.WriteLine(value);
- }
- Console.WriteLine(matrix.Length);
- Console.WriteLine(matrix.GetLength(0));
- Console.WriteLine(matrix.GetLength(1));
- }
- Print(matrix);
- // Analyzes(matrix);
- RemoveIslands(matrix, linkBorder);
- Console.WriteLine("=========================");
- Print(matrix);
- // Inspired from: https://www.youtube.com/watch?v=4tYoVx0QoN0&t=2518s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement