|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int dr[4] = {-1, 1, 1, -1}; |
| 4 | + int dc[4] = {1, 1, -1, -1}; |
| 5 | + |
| 6 | + bool inBounds(int r, int c, int n, int m) { |
| 7 | + return r >= 0 && r < n && c >= 0 && c < m; |
| 8 | + } |
| 9 | + |
| 10 | + int dfs(vector<vector<int>>& grid, int r, int c, int dir, bool canChange, int len, int searchFor) { |
| 11 | + int n = grid.size(); |
| 12 | + int m = grid[0].size(); |
| 13 | + int maxi = len; |
| 14 | + |
| 15 | + if (dir != -1) { |
| 16 | + int nr = r + dr[dir]; |
| 17 | + int nc = c + dc[dir]; |
| 18 | + if (inBounds(nr, nc, n, m) && grid[nr][nc] == searchFor) { |
| 19 | + int nextVal = (searchFor == 2) ? 0 : 2; |
| 20 | + maxi = max(maxi, dfs(grid, nr, nc, dir, canChange, len + 1, nextVal)); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + if (dir != -1 && canChange) { |
| 25 | + int ndir = (dir + 1) % 4; |
| 26 | + int nr = r + dr[ndir]; |
| 27 | + int nc = c + dc[ndir]; |
| 28 | + if (inBounds(nr, nc, n, m) && grid[nr][nc] == searchFor) { |
| 29 | + int nextVal = (searchFor == 2) ? 0 : 2; |
| 30 | + maxi = max(maxi, dfs(grid, nr, nc, ndir, false, len + 1, nextVal)); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + if (dir == -1) { |
| 35 | + for (int i = 0; i < 4; i++) { |
| 36 | + int nr = r + dr[i]; |
| 37 | + int nc = c + dc[i]; |
| 38 | + if (inBounds(nr, nc, n, m) && grid[nr][nc] == searchFor) { |
| 39 | + int nextVal = (searchFor == 2) ? 0 : 2; |
| 40 | + maxi = max(maxi, dfs(grid, nr, nc, i, canChange, len + 1, nextVal)); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return maxi; |
| 46 | + } |
| 47 | + |
| 48 | + int lenOfVDiagonal(vector<vector<int>>& grid) { |
| 49 | + int n = grid.size(); |
| 50 | + int m = grid[0].size(); |
| 51 | + int maxi = 0; |
| 52 | + |
| 53 | + for (int i = 0; i < n; i++) { |
| 54 | + for (int j = 0; j < m; j++) { |
| 55 | + if (grid[i][j] == 1) { |
| 56 | + maxi = max(maxi, dfs(grid, i, j, -1, true, 1, 2)); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return maxi; |
| 61 | + } |
| 62 | +}; |
0 commit comments