题目描述
题目思路
用一个BFS来遍历,每次(nx,ny)的下一步有两个点可以走(nx,ny+1),(nx+1, ny),这种情况下,用一个队列来存储 .
代码
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
vector<int> ans;
queue <pair<int, pair<int, int>>> q;
int m = nums.size(), n = nums[0].size();
for(int i = 0;i < m;i++){
if(nums[i].size() > n) n = nums[i].size();
}
vector<vector<bool>> vis(m, vector<bool>(n, false));
q.push(make_pair(nums[0][0], make_pair(0,0)));
pair<int, pair<int,int>> curPos;
vis[0][0] = true;
while(!q.empty()){
curPos = q.front();
q.pop();
int val = curPos.first, nx = curPos.second.first, ny = curPos.second.second;
ans.push_back(val);
if(nx + 1 < m && ny < nums[nx + 1].size()){
if (!vis[nx+1][ny]){
q.push(make_pair(nums[nx + 1][ny], make_pair(nx + 1, ny)));
vis[nx+1][ny] = true;
}
}
if(nx < m && ny + 1 < nums[nx].size()){
if (!vis[nx][ny + 1]){
q.push(make_pair(nums[nx][ny + 1], make_pair(nx, ny + 1)));
vis[nx][ny + 1] = true;
}
}
}
return ans;
}
};
ps:因为数组并不是等长的,因此需要判断列上面的最长值,然后再去找相应的数值.