14503ロボット掃除機


https://www.acmicpc.net/problem/14503
DFSまたは反復文で解決できる問題.
簡単な複文で説明した.
direct = (direct + 3) % 4;
左回転の表現は以下の通りです.
(北:0,東:1,南:2,西:3)
int[][] goBack = {
                {-1, 0, 1, 0},
                {0, 1, 0, -1},
                {1, 0, -1, 0},
                {0, -1, 0, 1}
        };
直線、列の変化、
後退する行、列の変化の2 D配列です.
(4つのプライマリアレイも表示可能)
ex)東向き直進
=>(現在行座標+goBack[1][0]、現在列座標+goBack[1])
東へ逆行する
=>(現在行座標+goBack[1][2]、現在列座標+goBack[1][3])
問題で提起された条件に従う.
まず左側
  • へ移動
    掃除がされていない場合は、
  • を参照してください.
  • 4箇所すべて捜査している間に、壁であれば終わり、バックできるならバックします.
    (掃除しない:0、壁:1、掃除:2)
  • 完全なコード
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
    
            int n = sc.nextInt();
            int m = sc.nextInt();
    
            int[][] arr = new int[n][m];
            int[][] goBack = {
                    {-1, 0, 1, 0},
                    {0, 1, 0, -1},
                    {1, 0, -1, 0},
                    {0, -1, 0, 1}
            };
    
            int row = sc.nextInt();
            int col = sc.nextInt();
            int direct = sc.nextInt();
    
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    arr[i][j] = sc.nextInt();
    
    
            int result = 0;
            int meet = 0;
    
            if(arr[row][col] == 0) {
                arr[row][col] = 2;
                result++;
            }
    
            while(true) {
    
                if(meet == 4) {
                    if(arr[row + goBack[direct][2]][col + goBack[direct][3]] == 1)
                        break;
    
                    else {
                        row += goBack[direct][2];
                        col += goBack[direct][3];
                        meet = 0;
                    }
                }
    
                direct = (direct + 3) % 4;
    
                if(arr[row + goBack[direct][0]][col + goBack[direct][1]] == 0) {
                    row += goBack[direct][0];
                    col += goBack[direct][1];
                    arr[row][col] = 2;
                    result++;
                    meet = 0;
                }
    
                else
                   meet++;
    
            }
    
            System.out.println(result);
        }
    }