公式

C - Rotate 解説 by en_translator


Considering the moves of the outer squares, they can be divided into the following four groups:

  • For integers \(i\) with \(1 \le i \le N-1\), the integer on square \((1,i)\) shifts to square \((1,i+1)\).
  • For integers \(i\) with \(1 \le i \le N-1\), the integer on square \((i,N)\) shifts to square \((i+1,N)\).
  • For integers \(i\) with \(2 \le i \le N\), the integer on square \((N,i)\) shifts to square \((N,i-1)\).
  • For integers \(i\) with \(2 \le i \le N\), the integer on square \((i,1)\) shifts to square \((i-1,1)\).

So, determine if each square is an outer square. If it is, shift it as described above; otherwise, do not; then the resulting grid can be found. The complexity is \(\mathrm{O}(N^2)\).

Here, if you use an integer type like int to receive the input, a sequence of input like 1011 is received as an integer \(1011\), so a trick is required here, like receiving it as a string and then decomposing it into characters.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
int main(){
  int n;
  cin>>n;
  vector<vector<int>> a(n,vector<int>(n));
  for(int i=0;i<n;i++){
    string s;
    cin>>s;
    for(int j=0;j<n;j++){
      if(s[j]=='0') a[i][j]=0;
      else a[i][j]=1;
    }
  }
  vector<vector<int>> ans(n,vector<int>(n));
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      if(i==0||j==0||i==n-1||j==n-1){
        if(i==0&&j<n-1) ans[i][j+1]=a[i][j];
        if(i<n-1&&j==n-1) ans[i+1][j]=a[i][j];
        if(i==n-1&&j>0) ans[i][j-1]=a[i][j];
        if(i>0&&j==0) ans[i-1][j]=a[i][j];
      }
      else{
        ans[i][j]=a[i][j];
      }
    }
  }
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++) cout<<ans[i][j];
    cout<<endl;
  }
}

投稿日時:
最終更新: