UTPC2011 D "停止問題"

問題:http://atcoder.jp/problem/detail/28

コード

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int r = s.nextInt(), c = s.nextInt(), m = 15;
		char[][] cs = new char[r][];
		for (int i = 0; i < r; ++i) {
			cs[i] = s.next().toCharArray();
		}
		boolean[][][][] b = new boolean[r][c][4][m + 1];
		Deque<int[]> q = new ArrayDeque<int[]>();
		q.push(new int[] { 0, 0, 1, 0 });
		int[][] ds = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };
		while (!q.isEmpty()) {
			int[] p = q.pop();
			int i = (p[0] + r) % r, j = (p[1] + c) % c, d = p[2], v = p[3];
			if (b[i][j][d][v]) {
				continue;
			}
			b[i][j][d][v] = true;
			switch (cs[i][j]) {
			case '<':
				d = 0;
				break;
			case '>':
				d = 1;
				break;
			case '^':
				d = 2;
				break;
			case 'v':
				d = 3;
				break;
			case '_':
				d = v < 1 ? 1 : 0;
				break;
			case '|':
				d = v < 1 ? 3 : 2;
				break;
			case '?':
			case '.':
				break;
			case '@':
				System.out.println("YES");
				return;
			case '+':
				v = v == m ? 0 : v + 1;
				break;
			case '-':
				v = v == 0 ? m : v - 1;
				break;
			default:
				v = cs[i][j] - '0';
				break;
			}
			if (cs[i][j] == '?') {
				for (int x = 0; x < 4; ++x) {
					q.push(new int[] { i + ds[x][0], j + ds[x][1], x, v });
				}
			} else {
				q.push(new int[] { i + ds[d][0], j + ds[d][1], d, v });
			}
		}
		System.out.println("NO");
	}

}