UnionFindなどを用いて移動先のマスと結合し、 グリッド外へ移動するようなマスを超頂点と連結することで 行動を終えることができるマスの数を求めることができます。
xxxxxxxxxx
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int H = sc.nextInt();
int W = sc.nextInt();
char[][] map = new char[H][];
for(int i=0;i<H;i++){
map[i] = sc.next().toCharArray();
}
UnionFind uf = new UnionFind(H*W+1);
for(int i=0;i<H;i++){
for(int j=0;j<W;j++){
switch(map[i][j]){
case 'U':
uf.unite(i*W+j,0<i?(i-1)*W+j:H*W);
break;
case 'R':
uf.unite(i*W+j,j<W-1?i*W+j+1:H*W);
break;
case 'D':
uf.unite(i*W+j,i<H-1?(i+1)*W+j:H*W);
break;
case 'L':
uf.unite(i*W+j,0<j?i*W+j-1:H*W);
break;
}
}
}
System.out.println(H*W-uf.size(H*W)+1);
}
}
//viral's Library
final class UnionFind {
private final int[] par, rank, size, path;
private int count;
public UnionFind ( final int N ) {
count = N;
par = new int[N];
rank = new int[N];
size = new int[N];
path = new int[N];
java.util.Arrays.fill( par, -1 );
java.util.Arrays.fill( size, 1 );
}
public int root ( final int ind ) {
if ( par[ind] == -1 ) {
return ind;
}
else {
return par[ind] = root( par[ind] );
}
}
public boolean isSame ( final int x, final int y ) {
return root( x ) == root( y );
}
public boolean unite ( final int x, final int y ) {
int rx = root( x );
int ry = root( y );
++path[rx];
if ( rx == ry ) {
return false;
}
if ( rank[rx] < rank[ry] ) {
int temp = rx;
rx = ry;
ry = temp;
}
par[ry] = rx;
if ( rank[rx] == rank[ry] ) {
++rank[rx];
}
path[rx] += path[ry];
size[rx] += size[ry];
--count;
return true;
}
public int groupCount () {
return count;
}
public int pathCount ( final int x ) {
return path[root( x )];
}
public int size ( final int x ) {
return size[root( x )];
}
}