AOJ 0151 Grid

問題

Grid

解法

縦横斜めで走査していって1の数をカウントする 斜めに走査するループの回し方が自分で書いたのにどうなってるのかよくわからない

コード

int n;
char grid[256][256];

int solve(){
  int res = 0, c;
  rep(i, n){
    c = 0;
    rep(j, n){
      if(grid[i][j] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  rep(j, n){
    c = 0;
    rep(i, n){
      if(grid[i][j] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  rep(i, n){
    c = 0;
    rep(j, n){
      if(i - j < 0) break;
      if(grid[j][i-j] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  rep(i, n){
    c = 0;
    rep(j, n){
      if(n-j < 0 || n-i+j-1 >= n || n-i+j-1 < 0) break;
      if(grid[n-i+j-1][n-j] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  rep(i, n){
    c = 0;
    rep(j, n){
      if(n - i + j - 1>= n) break;
      if(grid[j][n-i+j-1] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  rep(i, n){
    c = 0;
    rep(j, n){
      if(i + j >= n) break;
      if(grid[i+j][j] == '1') res = max(res, ++c);
      else c = 0;
    }
  }

  return res;
}

int main(){
  while(scanf("%d", &n) && n){
    memset(grid, 0, sizeof(grid));
    rep(i, n) scanf("%s", grid[i]);
    printf("%d\n", solve());
  }
  return 0;
}