Skip to content

Instantly share code, notes, and snippets.

@mi6112ogit
Created September 18, 2017 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mi6112ogit/95359f3f435df4cdb2e4a5654bd9b316 to your computer and use it in GitHub Desktop.
Save mi6112ogit/95359f3f435df4cdb2e4a5654bd9b316 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
#define FOR(i, j, k) for(int i = j; i < k; ++i)
#define rep(i, j) FOR(i, 0, j)
#define INF (1 << 30)
#define fi first
#define se second
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<P, int> Pi;
typedef pair<P, P> PP;
const int MOD = 1e9 + 7;
const int dy[]={0, 0, 1, -1};
const int dx[]={1, -1, 0, 0};
template <class T> void chmin(T& a, const T& b) { a = min(a, b); }
template <class T> void chmax(T& a, const T& b) { a = max(a, b); }
int w, h;
int field[20][20];
int sx, sy, res = INF;
void dfs(int x, int y, int cnt) {
if(cnt + 1 > 10) return;
rep(i, 4) {
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || nx >= w || ny < 0 || ny >= h || field[ny][nx] == 1) {
continue;
}
while(1) {
if(nx < 0 || nx >= w || ny < 0 || ny >= h || field[ny][nx] == 1) break;
if(field[ny][nx] == 3) {
chmin(res, cnt + 1);
return;
}
nx += dx[i]; ny += dy[i];
}
if(0 <= nx && nx < w && 0 <= ny && ny < h) {
field[ny][nx] = 0;
dfs(nx - dx[i], ny - dy[i], cnt + 1);
field[ny][nx] = 1;
}
}
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
while(scanf("%d %d", &w, &h), w | h) {
rep(i, h) rep(j, w) {
scanf("%d", &field[i][j]);
if(field[i][j] == 2) {
sx = j; sy = i;
}
}
res = INF;
dfs(sx, sy, 0);
printf("%d\n", (res != INF) ? res : -1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment