2684. 矩阵中移动的最大次数
class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
ret = 0
m, n = len(grid), len(grid[0])
visited = set()
for i in range(m):
if (i, 0) in visited: continue
q = collections.deque([(i, 0, 0)])
visited.add((i, 0))
while q:
x, y, step = q.popleft()
ret = max(ret, step)
for nx, ny in (x - 1, y + 1), (x, y + 1), (x + 1, y + 1):
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] > grid[x][y] and (nx, ny) not in visited:
q.append((nx, ny, step + 1))
visited.add((nx, ny))
return ret
class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
self.ret = 0
m, n = len(grid), len(grid[0])
visited = set()
def dfs(x, y, step):
self.ret = max(self.ret, step)
visited.add((x, y))
for nx, ny in (x - 1, y + 1), (x, y + 1), (x + 1, y + 1):
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] > grid[x][y] and (nx, ny) not in visited:
dfs(nx, ny, step + 1)
for i in range(m):
dfs(i, 0, 0)
return self.ret
unordered_set文档
class Solution {
public:
int maxMoves(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int ret = 0;
vector<vector<int>> visited(m, vector<int>(n));
for (int i = 0; i < m; ++i){
if (visited[i][0]) continue;
queue<vector<int>> q;
q.push({i, 0, 0});
visited[i][0] = true;
while (!q.empty()){
int x = q.front()[0], y = q.front()[1], step = q.front()[2]; q.pop();
ret = max(ret, step);
int dx[3] = {-1, 0, 1};
int dy[3] = {1, 1, 1};
for (int idx = 0; idx < 3; ++idx){
int nx = x + dx[idx], ny = y + dy[idx];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] > grid[x][y] && !visited[nx][ny]){
q.push({nx, ny, step + 1});
visited[nx][ny] = true;
}
}
}
}
return ret;
}
};