Problem:
城の堀
いま、忍者が城外から天守閣に忍び入ろうと計画を立てています。この忍者は地面を走ったり、堀の中を泳いだりすることは難なくできますが、堀から這い上がることはとても苦手なので、忍者は堀に入る回数をできるだけ少なくしたいと考えています。
お城の見取図を入力とし、城外から天守閣に至るまでに、堀から這い上がらなくてはならない最小回数を出力するプログラムを作成して下さい。お城の見取図は二次元格子として与えられます。見取り図に描かれた記号には、天守閣の位置を示す「&」と堀の位置を示す「#」の位置が記され、そのほかの地点には「.」（半角ピリオド）が記されています。なお、お城には天守閣は一つだけあるものとし、忍者は走ったり泳いだりして移動するときに東西南北方向に1マスずつ移動するものとし、斜めには移動しません。
Input
複数のデータセットの並びが入力として与えられます。入力の終わりはゼロ２つの行で示されます。各データセットは以下の形式で与えられます。
n
m
c
1,1
c
1,2
...
c
1,n
c
2,1
c
2,2
...
c
2,n
:
c
m,1
c
m,2
...
c
m,n
１行目に見取図の東西の幅
n
と 南北の幅
m
(1 ≤
n
,
m
≤ 100) が与えられる。続く
m
行に見取り図の
i
行目の情報が与えられる。各情報は記号「&」、「#」、「.」からなる長さ
n
の文字列である。
データセットの数は 50 を越えない。
Output
データセットごとに堀から這い上がらなくてはならない最小回数（整数）を１行に出力します。
Sample Input
5 5
.###.
#...#
#.&.#
#...#
.###.
18 15
..####....####....
####..####....####
#...............##
.#.############.##
#..#..........#.##
.#.#.########.#.##
#..#.#......#.#.##
.#.#....&...#.#.##
#..#........#.#.##
.#.#.########.#.##
#..#..........#.##
.#.############.##
#...............##
.#################
##################
9 10
#########
........#
#######.#
#.....#.#
#.###.#.#
#.#&#.#.#
#.#...#.#
#.#####.#
#.......#
#########
9 3
###...###
#.#.&.#.#
###...###
0 0
</pre>

<H2>Output for the Sample Input</H2>

<pre>
1
2
0
0
</pre>

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
const int INF = (1<<30);
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
string c[110];
int n, m, cost[110][110];
void dfs(int x, int y){
    for(int i=0;i<4;i++){
        int nx = x+dx[i];
        int ny = y+dy[i];
        if(nx<0||nx>=n||ny<0||ny>=m) continue;
        int ncost = cost[y][x];
        if(c[y][x]=='#' && c[ny][nx]=='.') ncost++;
        if(cost[ny][nx] > ncost){
            cost[ny][nx] = ncost;
            dfs(nx, ny);
        }
    }
}
int main(){
    int sx, sy, mi;
    while(cin >> n >> m, n!=0){
        for(int i=0;i<m;i++){
            cin >> c[i];
            for(int j=0;j<n;j++){
                if(c[i][j]=='&'){
                    sx = j;
                    sy = i;
                }
                cost[i][j] = INF;
            }
        }
        cost[sy][sx] = 0;
        dfs(sx, sy);
        mi = INF;
        for(int i=0;i<m;i++){
            if(c[i][0]=='#') cost[i][0]++;
            if(c[i][n-1]=='#') cost[i][n-1]++;
            mi = min(mi, cost[i][0]);
            mi = min(mi, cost[i][n-1]);
        }
        for(int i=0;i<n;i++){
            if(c[0][i]=='#') cost[0][i]++;
            if(c[m-1][i]=='#') cost[m-1][i]++;
            mi = min(mi, cost[0][i]);
            mi = min(mi, cost[m-1][i]);
        }
        cout << mi << endl;
    }
    return(0);
}
accuracy: 1
time_ms: 390
memory_kb: 3600
final_rank: 19

code_snippet: #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define lol(i,n) for(int i=0;i<n;i++)
#define mod 1000000007
typedef long long ll;
using namespace std;
int dis[110][110],p[110][110];
typedef pair<int,pair<int,int> >P;
priority_queue<P,vector<P>,greater<P> >Q;
void Qpush(int a,int b,int c){Q.push(make_pair(a,make_pair(b,c)));}
int main(){
  int h,w;
  while(cin>>w>>h&&h+w){
    lol(i,h)lol(j,w){
      char z;cin>>z;
      if(z=='&')Qpush(0,i,j);
      if(z=='#')p[i][j]=1;
      else p[i][j]=0;
      dis[i][j]=mod;
    }
    while(!Q.empty()){
      int cost=Q.top().first;
      int y=Q.top().second.first;
      int x=Q.top().second.second;
      Q.pop();
      if(dis[y][x]<=cost)continue;
      dis[y][x]=cost;
      int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
      lol(i,4){
	int xx=x+dx[i],yy=y+dy[i];
	if(xx<0||xx==w||yy<0||yy==h)continue;
	int newcost=cost+(p[y][x]!=p[yy][xx]);
	if(dis[yy][xx]>newcost)Qpush(newcost,yy,xx);
      }
    }
    int ans=mod;
    for(int i=0;i<h;i++)ans=min(ans,min(dis[i][0],dis[i][w-1]));
    for(int j=0;j<w;j++)ans=min(ans,min(dis[0][j],dis[h-1][j]));
    cout<<(ans+1)/2<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3224
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std ;

#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) begin(r),end(r)
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init))
#define mp(a,b) make_pair(a,b)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;

const int mod = 1000000007;
constexpr ll inf = ((1<<30)-1)*2+1 ;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};

inline bool value(int x,int y,int w,int h){
  return (x >= 0 && x < w && y >= 0 && y < h);
}

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll n,m;
  while(cin >> n >> m && n+m){
    vector<vector<char>> v(m+1,vector<char>(n+1,' '));
    using piii = pair<int,pair<int,int>>;
    priority_queue<piii> q;
    vector<vector<int>> d(m+1,vector<int>(n+1,inf));
    {
      int x = 0,y = 0;
      rep(j,m){
        rep(i,n){
          cin >> v[j][i];
          if(v[j][i] == '&'){
            x = i;
            y = j;
          }
        }
      }
      piii pos = mp(0,mp(y,x));
      d[y][x] = 0;
      q.push(pos);
    }
    int ans = inf;
    while(q.size()){
      auto Q = q.top();q.pop();
      auto p = Q.se;
      int dpt = Q.fi;
      int x = p.se,y = p.fi;
      rep(i,4){
        int nx = x + dx[i],ny = y + dy[i];
        if(value(nx,ny,n,m)){
          if(v[y][x] == v[ny][nx] && d[ny][nx] > d[y][x]){
            d[ny][nx] = d[y][x];
            q.push(mp(-dpt,mp(ny,nx)));
          }
          else if(d[ny][nx] > d[y][x] + (v[ny][nx] == '#')){
            d[ny][nx] = (v[ny][nx] == '#') + d[y][x];
            q.push(mp(-(dpt+1),mp(ny,nx)));
          }
        }
        else{
          ans = min(ans,d[y][x]);
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3608
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define INF (1<<29)

typedef pair<int, int> pii;

int main() {
	int n, m;
	while (cin >> n >> m, n || m) {
		vector<vector<int> > cnt(m, vector<int>(n, INF));
		vector<string> str(m);
		REP(i, m) cin >> str[i];
		
		priority_queue<pair<int, pii>, vector<pair<int, pii> >, greater<pair<int, pii> > > pq;
		REP(i, m) {
			pq.push(make_pair(str[i][0] == '#', pii(i, 0)));
			pq.push(make_pair(str[i][n - 1] == '#', pii(i, n - 1)));
		}
		REP(i, n) {
			pq.push(make_pair(str[0][i] == '#', pii(0, i)));
			pq.push(make_pair(str[m - 1][i] == '#', pii(m - 1, i)));
		}
		
		while (!pq.empty()) {
			pair<int, pii> now = pq.top();
			pq.pop();
			
			int x = now.second.second, y = now.second.first;
			if (cnt[y][x] != INF) continue;
			cnt[y][x] = now.first;
			
			if (str[y][x] == '&') {
				cout << cnt[y][x] << endl;
				break;
			}
			
			int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
			REP(i, 4) {
				int nx = x + dx[i], ny = y + dy[i];
				if (!(nx >= 0 && nx < n && ny >= 0 && ny < m)) continue;
				pq.push(make_pair(cnt[y][x] + (str[y][x] != '#' && str[ny][nx] == '#'), pii(ny, nx)));
			}
		}
	}
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1532
final_rank: 12

code_snippet: #include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef pair<int,pii> pip;
typedef vector<pip>vip	;
const double PI=acos(-1);
const double EPS=1e-8;
const int inf=1<<30;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int dp[110][110];
int main(){
	int n,m;
	while(cin>>m>>n,n+m){
		vector<string>in(n);
		rep(i,n)cin>>in[i];
		queue<pip>q;
		int sx,sy;
		rep(i,110)rep(j,110)dp[i][j]=inf;
		rep(i,n)rep(j,m)if(i==0||j==0||i==n-1||j==m-1){
			if(in[i][j]!='#'){
				q.push(pip(i,pii(j,0)));
				dp[i][j]=0;
			}else{
				q.push(pip(i,pii(j,1)));
				dp[i][j]=1;
			}
		}
		rep(i,n)rep(j,m)if(in[i][j]=='&')sx=i,sy=j;
		while(!q.empty()){
			pip p=q.front();
			q.pop();
			int x=p.first,y=p.second.first,cost=p.second.second;
//			cout<<x<<" "<<y<<" "<<cost<<endl;
			if(dp[x][y]<cost)continue;
			rep(k,4){
				int nx=x+dx[k],ny=y+dy[k];
				if(nx<0||ny<0||nx>=n||ny>=m)continue;
				int ncost=cost+(in[nx][ny]=='#'?1:0);
				if(in[nx][ny]=='#'&&in[x][y]=='#')ncost--;
//				cout<<" "<<nx<<" "<<ny<<" "<<ncost<<endl;
				if(dp[nx][ny]>ncost){
					dp[nx][ny]=ncost;
					q.push(pip(nx,pii(ny,ncost)));					
				}
			}
		}
		cout<<dp[sx][sy]<<endl;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 1312
final_rank: 3

code_snippet: #include <iostream>
#include <vector>
#include <queue>
#include <cmath>

using namespace std;

typedef pair<int, int> P;
typedef pair<P, int> Q;

int main() {
	int n, m;
	while (cin >> m >> n) {
		if (n == 0 && m == 0) {
			break;
		}
		vector< vector<char> > c(n, vector<char>(m));
		vector< vector<int> > d(n, vector<int>(m, 1000));
		int si, sj;
		si = sj = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cin >> c[i][j];
				if (c[i][j] == '&') {
					si = i;
					sj = j;
					c[si][sj] = '.';
				}
			}
		}
		d[si][sj] = 0;
		queue<Q> q;
		int di[] = {1, 0, -1, 0};
		int dj[] = {0, 1, 0, -1};
		q.push(Q(P(si, sj), 0));
		while (!q.empty()) {
			Q qq = q.front();
			q.pop();
			P pp = qq.first;
			for (int i = 0; i < 4; i++) {
				if (pp.first+di[i] >= 0 && pp.first+di[i] < n && pp.second+dj[i] >= 0 && pp.second+dj[i] < m) {
					int aa = qq.second;
					if (c[pp.first][pp.second] == '.' && c[pp.first+di[i]][pp.second+dj[i]] == '#') {
						aa++;
					}
					if (d[pp.first+di[i]][pp.second+dj[i]] > aa) {
						d[pp.first+di[i]][pp.second+dj[i]] = aa;
						q.push(Q(P(pp.first+di[i], pp.second+dj[i]), aa));
					}
				}
			}
		}
/*
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cout << d[i][j];
			}
			cout << endl;
		}
		*/
		int MIN = 1000;
		for (int i = 0; i < n; i++) {
			MIN = min(MIN, min(d[i][0], d[i][m-1]));
		}
		for (int i = 0; i < m; i++) {
			MIN = min(MIN, min(d[0][i], d[n-1][i]));
		}
		cout << MIN << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1284
final_rank: 2

code_snippet: #include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <functional>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <deque>
#include <ctime>
  
using namespace std;
  
#define rep(i,n) REP(i,0,n)
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define pb push_back
#define mp make_pair
#define all(r) r.begin(),r.end()
#define rall(r) r.rbegin(),r.rend()
#define fi first
#define se second
#define println(X) cout<<X<<endl;
#define DBG(X) cout<<#X<<" : "<<X<<endl;
  
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
 
const int INF = 1e9;
const ll MOD = 1e9 + 7;
double EPS = 1e-8;
const double PI = acos(-1);

//0156

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

int d[110][110];

bool isOutOfRange(int x, int y, int w, int h){
    if(x < 0 || x >= w || y < 0 || y >= h) return true;
    return false;
}

string s[110];

int main(){
    int x, y;
    int sx, sy;
    while(cin>>x>>y && x && y){
        rep(i, y) cin>>s[i];
        rep(i, y) rep(j, x){
            if(s[i][j] == '&'){
                sx = j;
                sy = i;
            }
            d[i][j] = INF;
        }
        //cout<<y<<" "<<x<<endl;
        priority_queue<pair<int, pii> > q;
        q.push(mp(0, mp(sy, sx)));
        d[sy][sx] = 0;
        pair<int, pii> p;
        int ans = INF;
        while(!q.empty()){
            p = q.top(); q.pop();
            //cout<<" "<<p.fi<<" ("<<p.se.fi<<", "<<p.se.fi<<endl;
            rep(i, 4){
                int nx = p.se.se + dx[i];
                int ny = p.se.fi + dy[i];
                if(isOutOfRange(nx, ny, x, y)){
                    ans = min(ans, -p.fi);
                    break;
                }
                int c = -p.fi + ((s[p.se.fi][p.se.se]!='#'&&s[ny][nx]=='#')?1:0);
                if(d[ny][nx] <= c) continue;
                d[ny][nx] = c;
                q.push(mp(-c, mp(ny, nx)));
            }
            if(ans != INF) break;
        }
        cout<<ans<<endl;
        // rep(i, y){
        //     rep(j, x){
        //         cout<<" "<<d[i][j];
        //     }
        //     cout<<endl;
        // }
    }
}
accuracy: 1
time_ms: 10
memory_kb: 1400
final_rank: 5

code_snippet: #include <queue>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

// ------ Class ------ //
class Graph2 {
public:
	static const long long INF = 1000000000000000000;
	int V, E; vector<vector<pair<int, long long> > > G;
	Graph2() : V(0), E(0), G(vector<vector<pair<int, long long> > >()) {}
	Graph2(int v) : V(v), E(0), G(vector<vector<pair<int, long long> > >(v)) {}
	Graph2(vector<vector<pair<int, long long> > > g) : V(g.size()), G(g) { for (int i = 0; i < g.size(); i++) E += g[i].size(); }
	int size() { return V; }
	void add1(int v1, int v2, long long w) { G[v1].push_back(make_pair(v2, w)); E++; }
	void add2(int v1, int v2, long long w) { add1(v1, v2, w); add1(v2, v1, w); }
	bool operator==(const Graph2& g) const { return G == g.G; }
	bool operator!=(const Graph2& g) const { return G != g.G; }
	vector<pair<int, long long> > operator[](int x) { return G[x]; }
	vector<long long> dist(int s) {
		priority_queue<pair<long long, int> > que; que.push(make_pair(0, s));
		vector<long long> d(V, INF); d[s] = 0;
		while (!que.empty()) {
			pair<long long, int> t = que.top(); que.pop();
			int u = t.second;
			for (int i = 0; i < G[u].size(); i++) {
				int v = G[u][i].first; long long e = G[u][i].second;
				if (d[v] > d[u] + e) {
					d[v] = d[u] + e;
					que.push(make_pair(-d[v], v));
				}
			}
		}
		return d;
	}
};

// ------ Main ------ //
int H, W, g; string s[100];
int main() {
	while (cin >> W >> H, H) {
		for (int i = 0; i < H; i++) cin >> s[i];
		Graph2 G(H * W + 1);
		for (int i = 0; i < H; i++) {
			for (int j = 1; j < W; j++) {
				G.add1(i * W + j - 1, i * W + j, (s[i][j - 1] == '#' && s[i][j] != '#') ? 1 : 0);
				G.add1(i * W + j, i * W + j - 1, (s[i][j - 1] != '#' && s[i][j] == '#') ? 1 : 0);
			}
		}
		for (int i = 1; i < H; i++) {
			for (int j = 0; j < W; j++) {
				G.add1(i * W + j - W, i * W + j, (s[i - 1][j] == '#' && s[i][j] != '#') ? 1 : 0);
				G.add1(i * W + j, i * W + j - W, (s[i - 1][j] != '#' && s[i][j] == '#') ? 1 : 0);
			}
		}
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) {
				if (i == 0 || i + 1 == H || j == 0 || j + 1 == W) G.add1(H * W, i * W + j, 0);
				if (s[i][j] == '&') g = i * W + j;
			}
		}
		cout << G.dist(H * W)[g] << endl;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 4204
final_rank: 17

code_snippet: #include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX_N 1000
int X[MAX_N][MAX_N], dist[MAX_N][MAX_N], W, H, gx, gy; char c;
int main() {
	while (true) {
		for (int i = 0; i < MAX_N; i++) {
			for (int j = 0; j < MAX_N; j++) {
				X[i][j] = 1000000000;
				dist[i][j] = 1000000000;
			}
		}
		cin >> W >> H; queue<pair<int, int>>Q;
		if (W == 0 && H == 0) { break; }
		for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= W; j++) {
				cin >> c;
				if (c == '&') { gx = i; gy = j; }
				if (c == '#') { X[i][j] = 1; }
				else { X[i][j] = 0; }
				if (i == 1 || i == H || j == 1 || j == W) {
					Q.push(make_pair(i, j));
					dist[i][j] = X[i][j];
				}
			}
		}
		while (!Q.empty()) {
			pair<int, int>pa = Q.front(); Q.pop();
			int cx = pa.first, cy = pa.second;
			int dx[4] = { 1,0,-1,0 };
			int dy[4] = { 0,1,0,-1 };
			for (int i = 0; i < 4; i++) {
				int ex = cx + dx[i], ey = cy + dy[i];
				if (X[ex][ey] >= 2) { continue; }
				int dis = dist[cx][cy];
				if (X[cx][cy] == 0 && X[ex][ey] == 1) {
					dis += 1;
				}
				if (dist[ex][ey]>dis) {
					dist[ex][ey] = dis;
					Q.push(make_pair(ex, ey));
				}
			}
		}
		cout << dist[gx][gy] << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 10956
final_rank: 18

code_snippet: #include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<climits>
using namespace std;

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

int N, M;

struct Data{
	int y, x, cost;
	Data(){}
	Data(int _y, int _x, int _cost){
		y = _y; x = _x; cost = _cost;
	}
};

bool IsOutside(int y, int x){
	return y < 0 || N <= y || x < 0 || M <= x;
}

int main(){
	while(cin >> N >> M, N || M){
		swap(N, M);
		
		char fld[100][100];
		queue<Data> q;
		Data q_front;
		int cost[100][100];
		fill_n( (int*)cost, 100*100, INT_MAX );

		for(int i = 0; i < N; i++){
			for(int j = 0; j < M; j++){
				cin >> fld[i][j];
				if(fld[i][j] == '&') q.push( Data(i, j, 0) );
			}
		}

		int ans = INT_MAX;
		while( !q.empty() ){
			q_front = q.front(); q.pop();
			if(cost[q_front.y][q_front.x] <= q_front.cost) continue;
			cost[q_front.y][q_front.x] = q_front.cost;

			for(int i = 0; i < 4; i++){
				int ny = q_front.y + dy[i], nx = q_front.x + dx[i];
				
				if( IsOutside(ny, nx) ){
					ans = min(ans, q_front.cost);
				}
				else{
					int cnt = 0;
					if(fld[q_front.y][q_front.x] != '#' && fld[ny][nx] == '#')
						cnt = 1;
					q.push( Data(ny, nx, q_front.cost + cnt) );
				}
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1276
final_rank: 1

code_snippet: #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <sstream>
#include <utility>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef pair<int , int>P;
typedef pair<P,P>PP;//wall dist y x
int M,N,mv[5]={-1,0,1,0,-1},res;
char B[105][105];
P d[105][105];

struct Order
{
	bool operator ()(PP const&a, PP const&b) const
	{
		if(a.first.first==b.first.first)
			return a.first.second>b.first.second;
		return a.first.first>b.first.first;
	}
};

priority_queue<PP,vector<PP>,Order>Q; //need finit

void Pset(int y, int x)
{
	d[y][x]=make_pair(0,0);
	Q.push(make_pair(make_pair(0,0),make_pair(y,x)));
}

int main()
{
	for (;scanf("%d%d\n" ,&N,&M),N+M;)
	{
		res=100000000;
		memset(d,0x7f, sizeof (d));
		for(int i=0;i<=M+1;i++)for(int j=0;j<=N+1;j++)B[i][j]='.';
		for(int i=0;i<M;i++)gets(B[i+1]+1);
		for(int i=0;i<=M+1;i++){B[i][N+1]='.';B[i][N+2]=0;}
		N++;M++;
		Q.push(make_pair(make_pair(0,0),make_pair(0,0)));
		while (!Q.empty())
		{
			PP tmp=Q.top();Q.pop();
			int y=tmp.second.first;
			int x=tmp.second.second;
			P cost=tmp.first;
			if (d[y][x]<cost)continue;
			if (B[y][x]=='&' )
			{
				res=min(res,cost.first);
				continue ;
			}
			for (int i=0;i<4;i++)
			{
				int ny=y+mv[i];
				int nx=x+mv[i+1];
				if (ny<0||ny>M||nx<0||nx>N) continue;
				P nc=make_pair(cost.first+(B[y][x]=='#' &&B[ny][nx]!= '#'),cost.second+1);
				if (nc<d[ny][nx])
				{
					d[ny][nx]=nc;
					Q.push(make_pair(nc,make_pair(ny,nx)));
				}
			}
		}
		printf( "%d\n" ,res);
	}
}
accuracy: 1
time_ms: 10
memory_kb: 1432
final_rank: 8

code_snippet: #include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<iostream>
#include<cmath>
#include<map>
#include<set>
#include<climits>
using namespace std;
typedef vector<string>vs;
typedef vector<int>vi;
typedef vector<vi>vvi;
typedef vector<double>vd;
typedef pair<int,int>pii;
typedef long long ll;
typedef pair<ll,ll>pll;
typedef vector<ll>vl;
typedef pair<int,pii>piii;
#define rrep(i,x,n) for(int i=(x);i<(n);++i)
#define rep(i,x) rrep(i,0,(x))
#define fi first
#define se second
#define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();++i)
#define all(c) (c).begin(),(c).end()
#define rall(c) (c).rbegin(),(c).rend()
#define pb push_back
#define maxs(a,b) (a)=max(a,b)
#define mins(a,b) (a)=min(a,b)
///#include<sstream>
///#include<cstring>
///#include<stack>
///#include<complex>

int W,H;
char fld[100][101];
const int dx[]={-1,0,1,0};
const int dy[]={0,-1,0,1};
int solve(){
    bool done[100][100]={{0}};
    priority_queue<piii,vector<piii>,greater<piii> >Q;
    rep(i,H){
        Q.push(piii(0,pii(i,0)));
        Q.push(piii(0,pii(i,W-1)));
    }
    rep(j,W){
        Q.push(piii(0,pii(0,j)));
        Q.push(piii(0,pii(H-1,j)));
    }

    while(!Q.empty()){
        piii p=Q.top();Q.pop();
        if(done[p.se.fi][p.se.se])continue;
        done[p.se.fi][p.se.se]=true;
        if(fld[p.se.fi][p.se.se]=='&')return p.fi;

        rep(i,4){
            int ty=p.se.fi+dy[i],tx=p.se.se+dx[i];
            if(ty<0||ty>=H||tx<0||tx>=W)continue;
            int tcost=p.fi;
            if(fld[p.se.fi][p.se.se]=='#'&&fld[ty][tx]!='#')tcost++;
            Q.push(piii(tcost,pii(ty,tx)));
        }
    }
}

int main(){
    while(scanf("%d%d",&W,&H),W||H){
        rep(i,H)scanf("%s",fld[i]);
        printf("%d\n",solve());
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1424
final_rank: 7

code_snippet: //「這い上がる」の定義があいまいなことから、エスパー力が本質っぽい問題だと思う。
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int,int> P;

int h, w;
char data[114][514];
int dp[552194];
queue<P> que;

int dy[4] = {1,0,-1,0};
int dx[4] = {0,1,0,-1};
int main(){
	int i,j;
	while (cin >> w >> h) {
		int g;
		if (!h) break;
		for (i = 0; i < h; i++) cin >> data[i];
		for (i = 0; i < w*h; i++) dp[i] = 5642194;
		for (i = 0; i < h; i++)
			for (j = 0; j < w; j++) {
				if (i == 0 || i == h-1 || j == 0 || j == w-1)
					que.push(P(0, i*w + j));
				if (data[i][j] == '&')
					g = i * w + j;
			}
		while(!que.empty()) {
			int cost = que.front().first;
			int pos = que.front().second;
			que.pop();
			if (dp[pos] <= cost)
				continue;
			dp[pos] = cost;
			for (i = 0; i < 4; i++) {
				int ny = pos/w + dy[i];
				int nx = pos%w + dx[i];
				if (ny < 0 || ny >= h || nx < 0 || nx >= w)
					continue;
				que.push( P( cost + (data[ny][nx] != '#' && data[pos/w][pos%w] == '#'), ny*w + nx ) );
			}
		}
		cout << dp[g] << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1332
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};

struct STATE
{
	int x, y, d;
	bool operator<(const STATE &t)const{
		return d > t.d;
	}
};

char grid[128][128];
int d[128][128];

bool ingrid(int x, int y, int w, int h)
{
	return x >= 0 && x <= h + 1 && y >= 0 && y <= w + 1;
}

int main()
{
	int w, h;
	while (scanf("%d %d", &w, &h), w + h){
		memset(grid, '.', sizeof(grid));
		for (int i = 0; i < 128; i++){
			for (int j = 0; j < 128; j++){
				d[i][j] = INF;
			}
		}

		int sx, sy;
		for (int i = 1; i <= h; i++){
			for (int j = 1; j <= w; j++){
				scanf(" %c", &grid[i][j]);
				if (grid[i][j] == '&'){
					sx = i;
					sy = j;
				}
			}
		}
		
		int res = 0;
		priority_queue<STATE> que;
		for (que.push({sx, sy, 0}); !que.empty(); que.pop()){
			STATE st = que.top();
			if (d[st.x][st.y] <= st.d) continue;
			d[st.x][st.y] = st.d;
			if (st.x == 0 || st.y == 0 || st.x == h + 1 || st.y == w + 1){
				res = st.d;
				break;
			}
			for (int dir = 0; dir < 4; dir++){
				int tx = st.x + dx[dir];
				int ty = st.y + dy[dir];
				if (!ingrid(tx, ty, w, h)) continue;
				if (d[tx][ty] > st.d + (grid[st.x][st.y] == '#')){
					que.push({tx, ty, st.d + (grid[st.x][st.y] == '#' && grid[tx][ty] == '.')});
				}
			}
		}
		printf("%d\n", res);
	}
	
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1420
final_rank: 6

code_snippet: #include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
//#include <utility>
#include <set>
#include <iostream>
//#include <memory>
#include <string>
#include <vector>
#include <algorithm>
//#include <functional>
#include <sstream>
//#include <deque>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
//#include <cctype>
#include <cstring>
//#include <ctime>
#include <iterator>
#include <bitset>
//#include <numeric>
//#include <list>
//#include <iomanip>

#if __cplusplus >= 201103L
#include <array>
#include <tuple>
#include <initializer_list>
#include <unordered_set>
#include <unordered_map>
#include <forward_list>

#define cauto const auto&
#else

#endif

using namespace std;


namespace{
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;

#define VV(T) vector<vector< T > >

template <class T>
void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()){
    v.assign(a, vector<T>(b, t));
}

template <class F, class T>
void convert(const F &f, T &t){
    stringstream ss;
    ss << f;
    ss >> t;
}


#define reep(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) reep((i),0,(n))
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define F first
#define S second
#define mkp make_pair
#define RALL(v) (v).rbegin(),(v).rend()


#define MOD 1000000007LL
#define EPS 1e-8
static const int INF=1<<24;
int dd[]={1,0,-1,0,1};

VV(char) vv;
vvint vis;
vvint tmp;
int h,w;
bool foo2(int a,int b){
	// cout<<a<<" "<<b<<endl;
	if(vv[a][b]==' ') return true;
	if(vis[a][b]) return false;
	if(tmp[a][b]==-1) return false;
	if(vv[a][b]=='#'&&tmp[a][b]==0){
		// vis[a][b]=1;
		tmp[a][b]=-1;
		return false;
	}
	// if(vv[a][b]=='#') return false;
	vis[a][b]=1;
	bool ret=false;
	rep(i,4){
		ret|=foo2(a+dd[i],b+dd[i+1]);
	}
	return ret;
}
void foo3(int a,int b){
	if(vv[a][b]!='#') return;
	tmp[a][b]=-1;
	rep(i,4){
		if(tmp[a+dd[i]][b+dd[i+1]]==-1) continue;
		foo3(a+dd[i],b+dd[i+1]);
	}
}
int foo(int c){
	// cout<<a<<" "<<b<<" "<<c<<endl;
	// rep(i,h+2){
		// rep(j,w+2){
			// cout<<tmp[i][j];
		// }
		// cout<<endl;
	// }
	// cout<<endl;
	// int a;
	// cin>>a;
	rep(i,h+2){
		rep(j,w+2){
			if(tmp[i][j]==1){
				// cout<<"aaa "<<endl;
				if(foo2(i,j)) return c;
			}
		}
	}
	rep(i,h+2){
		rep(j,w+2){
			if(tmp[i][j]==1){
				tmp[i][j]=2;
			}
		}
	}
	rep(i,h+2){
		rep(j,w+2){
			if(tmp[i][j]==-1){
				foo3(i,j);
			}
		}
	}
	rep(i,h+2){
		rep(j,w+2){
			if(tmp[i][j]==-1){
				tmp[i][j]=1;
			}
		}
	}
	return foo(c+1);
}

void mainmain(){
	// int w,h;
	while(cin>>w>>h,w||h){
		initvv(vv,h+2,w+2,' ');
		initvv(vis,h+2,w+2,0);
		initvv(tmp,h+2,w+2,0);
		reep(i,1,h+1){
			string s;
			cin>>s;
			reep(j,1,w+1){
				vv[i][j]=s[j-1];
				if(vv[i][j]=='&'){
					tmp[i][j]=1;
				}
			}
		}
		// rep(i,h+2){
			// rep(j,w+2){
				// cout<<vv[i][j];
			// }
			// cout<<endl;
		// }
		cout<<foo(0)<<endl;
	}
}



}
main() try{
    mainmain();
}
catch(...){
}
accuracy: 1
time_ms: 10
memory_kb: 1572
final_rank: 11

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;

const int dx[] = {1, -1, 0,  0};
const int dy[] = {0,  0, 1, -1};
char field[104][104];

int main() {
    int n, m;
    while (cin >> n >> m, n) {
        for (int i=0; i<104; ++i) {
            for (int j=0; j<104; ++j) {
                if (i % 103 == 0 || j % 103 == 0) {
                    field[i][j] = '*';
                } else {
                    field[i][j] = '.';
                }
            }
        }
        for (int i=2; i<=m+1; ++i) {
            for (int j=2; j<=n+1; ++j) {
                cin >> field[i][j];
            }
        }
        bool ok = false;
        int k = 0;
        for (; !ok; ++k) {
            queue<pair<int,int> > q;
            q.push(make_pair(1,1));
            while ( ! q.empty() && ! ok) {
                int x = q.front().first;
                int y = q.front().second;
                q.pop();
                for (int i=0; i<4; ++i) {
                    if (field[y + dy[i]][x + dx[i]] == '&') {
                        ok = true;
                        break;
                    }
                    if (field[y + dy[i]][x + dx[i]] == '.') {
                        field[y + dy[i]][x + dx[i]] = '#';
                        q.push(make_pair(x + dx[i], y + dy[i]));
                    }
                }
            }
            if (ok) break;
            queue<pair<int,int> > q2;
            q2.push(make_pair(1,1));
            while ( ! q2.empty()) {
                int x = q2.front().first;
                int y = q2.front().second;
                q2.pop();
                for (int i=0; i<4; ++i) {
                    if (field[y + dy[i]][x + dx[i]] == '#') {
                        field[y + dy[i]][x + dx[i]] = '.';
                        q2.push(make_pair(x + dx[i], y + dy[i]));
                    }
                }
            }
        }
        cout << k << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1224
final_rank: 10

code_snippet: #include <bits/stdc++.h>

//{{{ graph.hpp
#ifndef INCLUDE_GRAPH_HPP
#define INCLUDE_GRAPH_HPP
#include <vector>
namespace orislib {
struct Edge {
  typedef int weight_t;
  int from, to;
  weight_t w;
  Edge(int from, int to, weight_t w) : from(from), to(to), w(w) {}
  bool operator<(const Edge& e) const {
    return w != e.w ? w > e.w : from != e.from ? from < e.from : to < e.to;
  }
  static const weight_t INF;
};
const int Edge::INF=INT_MAX;
typedef std::vector<Edge> Edges;
typedef std::vector<Edges> Graph;
}
#endif
//}}}

using namespace std;
using namespace orislib;

typedef long long ll;
typedef long double ld;
typedef tuple<int, int> duo;
const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};
const int Mod = 1000000000 + 0;
//{{{ templates
#define TT_ template<typename T>inline
#define TTF_ template<typename T,typename F>inline
TT_ T sq(T x){return x*x;}
TT_ T In(){T x;cin>>x;return x;}
TT_ void Out(T&x){cout<<x;}
TT_ void sort(T&v){sort(begin(v),end(v));}
TT_ void revs(T&v){reverse(begin(v),end(v));}
TT_ void uniq(T&v){sort(v);v.erase(unique(begin(v),end(v)),end(v));}
TT_ int ubnd(T&v,typename T::value_type x){return upper_bound(begin(v),end(v),x)-begin(v);}
TT_ int lbnd(T&v,typename T::value_type x){return lower_bound(begin(v),end(v),x)-begin(v);}
TTF_ void inpt(T&v,int n,F f){for(v.reserve(n);n--;v.emplace_back(f()));}
TTF_ void show(T&v,F f,string d=" ",string e="\n"){int i=0;for(auto&x:v)i++&&(cout<<d),f(x);cout<<e;}
TT_ typename T::iterator minel(T&v){return min_element(begin(v),end(v));}
TT_ typename T::iterator maxel(T&v){return max_element(begin(v),end(v));}

inline void fast_io(){ios_base::sync_with_stdio(0);cin.tie(0);}
inline int in(){int x;scanf("%d",&x);return x;}
inline ll pow_mod(ll a,ll k,ll m){ll r=1;for(;k>0;a=a*a%m,k>>=1)if(k&1)r=r*a%m;return r;}
inline ll mod_inv(ll a,ll p){return pow_mod(a,p-2,p);}
//}}} priority_queue queue deque front stringstream max_element min_element insert count make_tuple

//{{{ void dijkstra(g, s, &dist, &prev)
void dijkstra(const Graph& g, int s, vector<Edge::weight_t>& dist, vector<int>& prev)
{
  const int V = g.size();
  prev.assign(V, -1);
  dist.assign(V, Edge::INF);
  dist[s] = 0;
  priority_queue<Edge> pq;
  for (pq.push(Edge(-2, s, 0)); !pq.empty();){
    Edge c = pq.top();
    pq.pop();
    if (prev[c.to] != -1) continue;
    prev[c.to] = c.from;
    for (const auto& e : g[c.to]){
      if (dist[e.to] > e.w + c.w){
        dist[e.to] = e.w + c.w;
        pq.push(Edge(e.from, e.to, e.w + c.w));
      }
    }
  }
}
//}}}

int main()
{
  int w, h;
  while (w = in(), h = in()){
    Graph g(w * h);
    char field[128][128];
    for (int i = 0; i < h; i++) scanf("%s", field[i]);
    int s;
    for (int i = 0; i < h; i++){
      for (int j = 0; j < w; j++){
        if (field[i][j] == '&'){
          s = i * w + j;
          field[i][j] = '.';
        }
        for (int d = 0; d < 4; d++){
          int nx = j + dx[d], ny = i + dy[d];
          if (nx < 0 || w <= nx || ny < 0 || h <= ny) continue;
          g[i * w + j].emplace_back(i * w + j, ny * w + nx, field[i][j] == '.' && field[ny][nx] == '#');
        }
      }
    }
    vector<int> dist, prev;
    dijkstra(g, s, dist, prev);
    int mini = 1000000;
    for (int i = 0; i < h; i++){
      mini = min(mini, dist[i * w]);
      mini = min(mini, dist[i * w + w - 1]);
    }
    for (int i = 0; i < w; i++){
      mini = min(mini, dist[i]);
      mini = min(mini, dist[(h - 1) * w + i]);
    }
    printf("%d\n", mini);
  }

  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 2248
final_rank: 14

code_snippet: #include <iostream>
#include <complex>
#include <sstream>
#include <string>
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <limits>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
#define REP(i, j) for(int i = 0; i < (int)(j); ++i)
#define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define REVERSE(v) reverse((v).begin(), (v).end())
typedef pair<int, int> P;
typedef pair<int, P> PP;
const int INF = 1e9;

int W, H, my[] = {0, 0, 1, -1}, mx[] = {1, -1, 0, 0};
vector< vector<char> > v;

int solve(){
  priority_queue<PP, vector<PP>, greater<PP> > open;
  open.push(PP(0, P(0, 0)));
  vector< vector<int> > closed(H, vector<int>(W, INF));
  while(!open.empty()){
    PP tmp = open.top(); open.pop();
    int y = tmp.second.first, x = tmp.second.second, cnt = tmp.first;
    if(closed[y][x] <= cnt) continue;
    closed[y][x] = cnt;
    REP(i, 4){
      int ny = y + my[i], nx = x + mx[i];
      if(ny >= 0 && nx >= 0 && ny < H && nx < W) open.push(PP((v[y][x] == '#' && v[ny][nx] != '#' ? cnt + 1 : cnt), P(ny, nx)));
    }
  }
  P tar;
  REP(i, H) REP(j, W) if(v[i][j] == '&') tar = P(i, j);
  return closed[tar.first][tar.second];
}

int main() {
  while(cin >>W >>H && W){
    H += 2; W += 2;
    v = vector< vector<char> >(H, vector<char>(W, '.'));
    FOR(i, 1, H - 1) FOR(j, 1, W - 1) cin >>v[i][j];
    cout <<solve() <<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1532
final_rank: 12

code_snippet: #include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

struct pos {
	int x, y;
	int cost;
	pos() {}
	pos(int x_, int y_, int cost_) {
		x = x_; y = y_; cost = cost_;
	}
	bool operator<(const pos p) const {
		return cost > p.cost;
	}
};

const int INF = 1000000;

int main() {
	int n, m;
	while(cin >> n >> m, n | m) {
		char in[128][128];
		int cost[128][128];
		for(int i = 0; i < 128; i++) {
			for(int j = 0; j < 128; j++) {
				in[i][j] = '.';
				cost[i][j] = INF;
			}
		}

		for(int i = 0; i < m; i++) {
			scanf("%s", in[i + 1] + 1);
			in[i + 1][n + 1] = '.';
		}

		priority_queue<pos> q;
		for(int i = 1; i < m + 1; i++) {
			for(int j = 1; j < n + 1; j++) {
				if(in[i][j] == '&') {
					q.push(pos(j, i, 0));
					i = m + 1;
					j = n + 1;
				}
			}
		}
		int dx[] = {-1, 1, 0, 0};
		int dy[] = {0, 0, -1, 1};
		int ans = -1;
		while(!q.empty()) {
			pos p;
			p = q.top(); q.pop();
			if(cost[p.y][p.x] == INF) {
				if(p.x <= 0 || n + 1 <= p.x || p.y <= 0 || m + 1 <= p.y) {
					ans = p.cost;
					break;
				}
				cost[p.y][p.x] = p.cost;
				for(int i = 0; i < 4; i++) {
					if(cost[p.y + dy[i]][p.x + dx[i]] == INF) {
						int c = p.cost;
						if(in[p.y][p.x] == '#' && in[p.y + dy[i]][p.x + dx[i]] == '.') {
							c++;
						}
						q.push(pos(p.x + dx[i], p.y + dy[i], c));
					}
				}
			}
		}

		/*
		for(int i = 1; i < m + 1; i++) {
			for(int j = 1; j < n + 1; j++) {
				cout << (cost[i][j] == INF ? in[i][j] : '*');
			}
			cout << endl;
		}
		*/
		cout << ans << endl;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 1436
final_rank: 9

code_snippet: #include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <set>
#include <cstring>
#include <cassert>

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,j) FOR(i,0,j)
#define mp std::make_pair

typedef long long ll;
typedef unsigned long long ull;
typedef std::pair<int,int> P;
typedef std::pair<int,P> State;

const int INF = 1001001001;

// S N E W(南北東西)
const int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1}, dy[8] = {1, -1, 0, 0, 1, -1, 1, -1};

int N, M; // N: x, M: y
int map[102][102];
bool used[1000][102][102];

int main(){
    while(std::cin >> N >> M, N){
        memset(used, 0, sizeof(used));
        memset(map, 0, sizeof(map));

        FOR(i, 1, M+1){
            FOR(j, 1, N+1){
                char c;
                std::cin >> c;
                if(c == '.'){map[i][j] = 0;}
                else if(c == '#'){map[i][j] = -1;}
                else{map[i][j] = 1;}
            }
        }
    
        std::priority_queue<State,std::vector<State>,std::greater<State>> q;
        REP(i, N+2){
            q.push(mp(0, mp(0, i)));
            q.push(mp(0, mp(M+1, i)));
        }

        REP(i, M+2){
            q.push(mp(0, mp(i, 0)));
            q.push(mp(0, mp(i, N+1)));
        }

        int res = -1;
        while(!q.empty()){
            State s = q.top(); q.pop();
            int t = s.first, y = s.second.first, x = s.second.second;

            if(t >= 1000){continue;}
            if(map[y][x] == 1){res = t; break;}
            if(used[t][y][x]){continue;}

            used[t][y][x] = true;
        
            REP(i, 4){
                int nx = x + dx[i], ny = y + dy[i];
                if(0 <= nx && nx <= N+1 &&
                   0 <= ny && ny <= M+1){
                    if(map[y][x] == 0 && map[ny][nx] == -1){
                        if(!used[t+1][ny][nx]){
                            q.push(mp(t+1, mp(ny, nx)));
                        }
                    }else{
                        q.push(mp(t, mp(ny, nx)));
                    }
                }
            }
        }

        assert(res != -1);
        std::cout << res << std::endl;
    }
}
accuracy: 1
time_ms: 230
memory_kb: 11628
final_rank: 20