AOJ1501 Grid

Grid | Aizu Online Judge

Introduction to Programming Introduction to Algorithms and Data Structures Library of Data Structures Library of Graph Algorithms Library of Computational Geometry Library of Dynamic Programming Library of Number Theory

愚直に幅優先で見て行くが,誤読に続く誤読を繰り返しとても時間がかかった.端と端が繋がるのは

1
2
int nx = (x + dx[i] + r) % r;
int ny = (y + dy[i] + c) % c;

と表現出来る.後は同じ深さの所は足していく.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>
#include <queue>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair
#define MOD 100000007

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

bool used[1005][1005];
ll cnt[1005][1005];
int depth[1005][1005];

int r, c;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

bool can(int x, int y) {
  if(0 <= x &&  x < r && 0 <= y && y < c) return true;
  return false;
}

int main() {
  int a1, a2, b1, b2;
  cin >> r >> c >> a1 >> a2 >> b1 >> b2;


  memset(used, 0, sizeof(used));
  used[a1][a2] = true;

  memset(cnt, 0, sizeof(cnt));
  cnt[a1][a2] = 1;

  memset(depth, 0, sizeof(depth));

  queue<P> que;
  que.push(mp(a1, a2));

  int ans = INF;
  while(que.size()) {
      P p = que.front(); que.pop();
      int x = p.first; int y = p.second;
      
      if(x == b1 && y == b2) {
          break;
      }

      rep(i, 4) {
          int nx = x + dx[i] + r;
          int ny = y + dy[i] + c;

          nx %= r; ny %= c;

          if(!used[nx][ny]) {
              cnt[nx][ny] += cnt[x][y];
              cnt[nx][ny] %= MOD;
              used[nx][ny] = true;
              depth[nx][ny] = depth[x][y] + 1;
              que.push(mp(nx, ny));
          } else if(depth[nx][ny] == depth[x][y] + 1) {
              cnt[nx][ny] += cnt[x][y];
              cnt[nx][ny] %= MOD;
          }
      }
  }

  cout << cnt[b1][b2] << endl;

  return 0;
}
Apr 20th, 2016