LoginSignup
0
0

More than 5 years have passed since last update.

迷路作り名人

Posted at

 いや〜はまってしまいました。幅優先、上手く書けないなぁ・・・。感覚を掴むまでが大事ですね。何度も書いてどう動いているか調べてみようと思います。

import java.util.*;
public class Main {

    int longestPath(String[] maze, int startRow, int startCol, int[] moveRow, int[] moveCol) {
        Queue<Integer> qx = new LinkedList<Integer>();
        Queue<Integer> qy = new LinkedList<Integer>();
        boolean[][] visit = new boolean[maze.length][maze[0].length()];

        qx.add(startRow);
        qy.add(startCol);
        int ans = -1;
        int count = 1;
        while(!qx.isEmpty()) {
            int nowX = qx.poll();
            int nowY = qy.poll();
            for(int r = 0; r < moveRow.length; r++) {
                int nextX = nowX + moveRow[r];
                int nextY = nowY + moveCol[r];
                if(nextX < 0 || nextY < 0 || nextX >= maze[r].length() || nextY >= maze.length) continue;
                if(visit[nextY][nextX] || maze[nextY].charAt(nextX) == 'X') continue;

                qx.add(nextX);
                qy.add(nextY);
                ans = Math.max(ans, count);
                count++;
                visit[nextY][nextX] = true;//訪れた事を記憶
            }
        }
        return(ans);
    }

    void doIt() {
        String[] maze = {
                "...",
                "...",
                "...",
                "...",
        };
        int startRow = 0;
        int startCol = 1;
        int[] moveRow = {1, 0, -1, 0};
        int[] moveCol = {0, 1, 0, -1};
        System.out.println(longestPath(maze, startRow, startCol, moveRow, moveCol));
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Main().doIt();
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0