A - Adjacent Squares Editorial by en_translator


We can easily come up with a solution of depending on lengthy conditional branches, but it is dangerous because it is easy to make mistakes. In this editorial, we will explain how to solve it as easily as possible.

Overall, we count how many of the following predicates are true:

  • There is a square in the left of Square \((R,C)\).
  • There is a square in the right of Square \((R,C)\).
  • There is a square above Square \((R,C)\).
  • There is a square below Square \((R,C)\).

We first consider when Square \((R,C)\) has a square in its left.
“There is a square in the left of Square \((R,C)\)” if and only if “\(C \neq 1\).”

We next consider when Square \((R,C)\) has a square in its right.
“There is a square in the right of Square \((R,C)\)” if and only if “\(C \neq W\).”

Same applies for vertical directions.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int h,w;
  int r,c;
  cin >> h >> w;
  cin >> r >> c;
  int res=0;
  if(c!=1){res++;}
  if(c!=w){res++;}
  if(r!=1){res++;}
  if(r!=h){res++;}
  cout << res << '\n';
  return 0;
}

posted:
last update: