classSolution{public:
vector<int>findBall(vector<vector<int>>& grid){int rows = grid.size();int cols = grid[0].size();
vector<int> ans;for(int i =0; i < grid[0].size(); i++){int pos = i;for(int j =0; j < grid.size(); j++){if(grid[j][pos]==1){// right is 1, go downif(pos == cols -1|| grid[j][pos +1]==-1){
pos =-1;break;}else{
pos +=1;}}elseif(grid[j][pos]=-1){// left is -1, go down, else stuckif(pos ==0|| grid[j][pos -1]==1){
pos =-1;break;}else{
pos -=1;}}}
ans.push_back(pos);}return ans;}};
1914. 循环轮转矩阵
代码实现(模拟)
classSolution{public:
vector<vector<int>>rotateGrid(vector<vector<int>>& grid,int k){constint rows = grid.size();constint cols = grid[0].size();constint times =min(rows /2, cols /2);
deque<int> cycle;for(int t =0; t < times; t++){int i = t, j = t;int r = rows -2* t;int c = cols -2* t;// cout << r << " " << c << endl;
cycle.clear();// read all the elementfor(int m = t; m < t + r; m++){
cycle.push_back(grid[m][t]);// cout << m << " " << t << endl;}for(int n = t +1; n < t + c; n++){
cycle.push_back(grid[r + t -1][n]);// cout << r + t - 1 << " " << n << endl;}for(int m = r + t -2; m >= t; m--){// cout << m << " " << t + c - 1 << endl;
cycle.push_back(grid[m][t + c -1]);}for(int n = t + c -2; n > t; n--){
cycle.push_back(grid[t][n]);// cout << t << " " << n << endl;}int curK = k %(2*(r + c)-4);for(int i =0; i < curK; i++){int tmp = cycle.back();// cout << tmp << endl;
cycle.pop_back();
cycle.push_front(tmp);}for(int m = t; m < t + r; m++){
grid[m][t]= cycle.front();
cycle.pop_front();}for(int n = t +1; n < t + c; n++){
grid[r + t -1][n]= cycle.front();
cycle.pop_front();}for(int m = r + t -2; m >= t; m--){
grid[m][t + c -1]= cycle.front();
cycle.pop_front();}for(int n = t + c -2; n > t; n--){
grid[t][n]= cycle.front();
cycle.pop_front();}}return grid;}};