プログラマメモ2 - programmer no memo2

1154 - レターズ 2011/09/24

1154 -- LETTERS
Javaです。
なんとかaccept...

package p1154; import java.util.Scanner; import java.util.Stack; public class Main { static class Cell { boolean used; char letter; public Cell(char letter) { this.letter = letter; } } static int solve(Cell[][] cells, int px, int py, Stack<Character> usedChar, int cnt) { if (!(0 <= px && 0 <= py)) return cnt; if ((cells[0].length <= py || cells.length <= px)) return cnt; Cell cell = cells[px][py]; if (cell.used){ return cnt; } if (usedChar.contains(cell.letter)){ return cnt; } cnt += 1; cell.used = true; usedChar.push(cell.letter); int a1 = solve(cells, px, py - 1, usedChar, cnt); int a2 = solve(cells, px - 1, py, usedChar, cnt); int a3 = solve(cells, px + 1, py, usedChar, cnt); int a4 = solve(cells, px, py + 1, usedChar, cnt); cnt = Math.max(a1, Math.max(a2, Math.max(a3, a4))); cell.used = false; usedChar.pop(); return cnt; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int R = scanner.nextInt(); int S = scanner.nextInt(); Cell[][] cells = new Cell[R][S]; for (int i = 0; i < R; i++) { String line = scanner.next(); char[] cs = line.toCharArray(); for (int j = 0; j < S; j++) { cells[i][j] = new Cell(cs[j]); } } Stack<Character> usedChar = new Stack<Character>(); int cnt = 0; cnt = solve(cells, 0, 0, usedChar, 0); System.out.print(cnt); } }

: