Official

B - Number Box Editorial by en_translator


First, exhaustively search for which square Takahashi will depart from.

Next, exhaustively search for which direction Takahashi should choose.

Then, we can uniquely determine the integer obtained by arranging the digits written on the squares visited by Takahashi from left to right in the order visited by him. Find their maximum value.

Since we need to handle integers with at most \(10\) digits, use a 64-bit integer type instead of 32-bit.

Implementation note: iteration over \(8\) directions can be easily implemented with an array like

vector<int> x={1,1,1,0,0,-1,-1,-1},y={1,0,-1,1,-1,1,0,-1}

Also, when the upper and lower edges and left and right edges are connected, managing the current coordinate \(\bmod\ N\) simplifies the implementation.

When finding the integer obtained by arranging the digits written on the squares visited by Takahashi from left to right in the order visited by him, a simple way is as follows: first prepare an integer \(X=0\), then every time you visit a square, multiply \(X\) by \(10\) and add to \(X\) the digit written on the current square.

Sample code in C++:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  int n;
  cin>>n;
  ll ans=0;
  vector<vector<ll>> a(n,vector<ll>(n));
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      char c;
      cin>>c;
      a[i][j]=c-'0';
    }
  }
  vector<int> p={1,1,1,0,0,-1,-1,-1},q={1,0,-1,1,-1,1,0,-1};
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      for(int k=0;k<8;k++){
        ll now=0;
        ll x=i,y=j;
        for(int l=0;l<n;l++){
          now*=10;
          now+=a[x][y];
          x+=p[k];
          y+=q[k];
          x%=n;
          x+=n;
          y%=n;
          y+=n;
          x%=n;
          y%=n;
        }
        ans=max(ans,now);
      }
    }
  }
  cout<<ans<<endl;
}

posted:
last update: