- Greedy, Matrix

Print the indices for every row of a grid from which escaping from the grid is possible

using System;class GFG {                static void findPath(int[, ] arr, int M, int N)    {                for (int row = 0; row < M; row++) {                                    char dir = 'L';                                    int i = row;                                    int j = 0;                        while (j < N) {                                if (arr[i, j] == 1) {                                        if (dir == 'L') {                                                i--;                                                dir = 'D';                    }                                        else if (dir == 'U') {                                                j--;                                                dir = 'R';                    }                                        else if (dir == 'R') {                                                i++;                                                dir = 'U';                    }                                        else if (dir == 'D') {                                                j++;                                                dir = 'L';                    }                }                                else {                                        if (dir == 'L') {                                                i++;                                                dir = 'U';                    }                                        else if (dir == 'U') {                                                j++;                                                dir = 'L';                    }                                        else if (dir == 'R') {                                                i--;                                                dir = 'D';                    }                                        else if (dir == 'D') {                                                j--;                                                dir = 'R';                    }                }                                                if (i < 0 || i == M || j < 0 || j == N)                    break;            }                        if (j == N)                Console.Write(i + " ");                        else                Console.Write(-1 + " ");        }    }           public static void Main()    {                       int[, ] arr = { { 1, 1, 0, 1 },                        { 1, 1, 0, 0 },                        { 1, 0, 0, 0 },                        { 1, 1, 0, 1 },                        { 0, 1, 0, 1 } };        int M = arr.GetLength(0);        int N = arr.GetLength(1);                findPath(arr, M, N);    }}