Overfencing - USACO 2.4.2


overfencing - codetrick
Farmer John went crazy and created a huge maze of fences out in a field. Happily, he left out two fence segments on the edges, and thus created two "exits" for the maze. Even more happily, the maze he created by this overfencing experience is a `perfect' maze: you can find a way out of the maze from any point inside it.
Given W (1 <= W <= 38), the width of the maze; H (1 <= H <= 100), the height of the maze; 2*H+1 lines with width 2*W+1 characters that represent the maze in a format like that shown later - then calculate the number of steps required to exit the maze from the `worst' point in the maze (the point that is `farther' from either exit even when walking optimally to the closest exit). Of course, cows walk only parallel or perpendicular to the x-y axes; they do not walk on a diagonal. Each move to a new square counts as a single unit of distance (including the move "out" of the maze.
Here's what one particular W=5, H=3 maze looks like:
+-+-+-+-+-+
|         |
+-+ +-+ + +
|     | | |
+ +-+-+ + +
| |     |  
+-+ +-+-+-+
Fenceposts appear only in odd numbered rows and and odd numbered columns (as in the example). The format should be obvious and self explanatory. Each maze has exactly two blank walls on the outside for exiting.

PROGRAM NAME: maze1

INPUT FORMAT

Line 1:W and H, space separated
Lines 2 through 2*H+2:2*W+1 characters that represent the maze

SAMPLE INPUT (file maze1.in)

5 3
+-+-+-+-+-+
|         |
+-+ +-+ + +
|     | | |
+ +-+-+ + +
| |     |  
+-+ +-+-+-+

OUTPUT FORMAT

A single integer on a single output line. The integer specifies the minimal number of steps that guarantee a cow can exit the maze from any possible point inside the maze.

SAMPLE OUTPUT (file maze1.out)

9
The lower left-hand corner is *nine* steps from the closest exit. 

X. Flood fill
http://qingtangpaomian.iteye.com/blog/1635853
          我们首先从输入输出中查找出迷宫的两个入口,然后以这两个入口为起点做floodfill为每个点产生同入口之间距离。然后遍历整个迷宫找出距离最远的输出即可。
floodfill图论当中的基本问题,注意积累一下。
  1.     public static void main(String[] args) throws Exception {  
  2.         Scanner in = new Scanner(System.in);  
  3.         PrintWriter pw = new PrintWriter(System.out); 
  4.         int width = in.nextInt();  
  5.         int height = in.nextInt();  
  6.         in.nextLine();  
  7.   
  8.         char[][] maze = new char[2 * height + 1][2 * width + 1];  
  9.         int[][] cnt = new int[2 * height + 1][2 * width + 1];  
  10.         int x1 = 0, y1 = 0;  
  11.         int x2 = 0, y2 = 0;  
  12.   
  13.         for (int i = 0; i < 2 * height + 1; i++) {  
  14.             String line = in.nextLine();  
  15.             for (int j = 0; j < 2 * width + 1; j++) {  
  16.                 char temp = line.charAt(j);  
  17.                 maze[i][j] = temp;  
  18.                 cnt[i][j] = Integer.MAX_VALUE;  
  19.                 if (temp == ' ') {  
  20.                     int tempx = 0;  
  21.                     int tempy = 0;  
  22.                     if (i == 0) {  
  23.                         tempx = i + 1;  
  24.                         tempy = j;  
  25.                     }  
  26.                     if (i == 2 * height) {  
  27.                         tempx = i - 1;  
  28.                         tempy = j;  
  29.                     }  
  30.                     if (j == 0) {  
  31.                         tempx = i;  
  32.                         tempy = j + 1;  
  33.                     }  
  34.                     if (j == 2 * width) {  
  35.                         tempx = i;  
  36.                         tempy = j - 1;  
  37.                     }  
  38.                     if (tempx!=0||tempy!=0){  
  39.                         if (x1 == 0 && y1 == 0) {  
  40.                             x1 = tempx;  
  41.                             y1 = tempy;  
  42.                         } else {  
  43.                             x2 = tempx;  
  44.                             y2 = tempy;  
  45.                         }  
  46.                     }  
  47.                 }  
  48.             }  
  49.         }  
  50.         cnt[x1][y1] = 1;  
  51.         flood(x1, y1, cnt, maze, width, height);  
  52.         cnt[x2][y2] = 1;  
  53.         flood(x2, y2, cnt, maze, width, height);  
  54.         int max = 0;  
  55.         for (int i = 1; i < 2 * height + 1; i += 2) {  
  56.             for (int j = 1; j < 2 * width + 1; j += 2) {  
  57.                 int temp = cnt[i][j];  
  58.                 if (cnt[i][j] != Integer.MAX_VALUE) {  
  59.                     if (max < cnt[i][j]) {  
  60.                         max = cnt[i][j];  
  61.                     }  
  62.                 }  
  63.             }  
  64.         }  
  65.         pw.println(max);  
  66.         pw.close();  
  67.     }  
  68.   
  69.     public static void flood(int x, int y, int[][] cnt, char[][] maze,  
  70.             int width, int height) {  
  71.         if (cnt[x][y] != 0) {  
  72.             if (x + 2 < 2 * height + 1 && maze[x + 1][y] == ' ') {  
  73.                 if (cnt[x + 2][y] > cnt[x][y] + 1) {  
  74.                     cnt[x + 2][y] = cnt[x][y] + 1;  
  75.                     flood(x + 2, y, cnt, maze, width, height);  
  76.                 }  
  77.   
  78.             }  
  79.             if (x - 2 >= 0 && maze[x - 1][y] == ' ') {  
  80.                 if (cnt[x - 2][y] > cnt[x][y] + 1) {  
  81.                     cnt[x - 2][y] = cnt[x][y] + 1;  
  82.                     flood(x - 2, y, cnt, maze, width, height);  
  83.                 }  
  84.   
  85.             }  
  86.             if (y + 2 < 2 * width + 1 && maze[x][y+1] == ' ') {  
  87.                 if (cnt[x][y + 2] > cnt[x][y] + 1) {  
  88.                     cnt[x][y + 2] = cnt[x][y] + 1;  
  89.                     flood(x, y + 2, cnt, maze, width, height);  
  90.                 }  
  91.   
  92.             }  
  93.             if (y - 2 >= 0 && maze[x][y-1] == ' ') {  
  94.                 if (cnt[x][y - 2] > cnt[x][y] + 1) {  
  95.                     cnt[x][y - 2] = cnt[x][y] + 1;  
  96.                     flood(x, y - 2, cnt, maze, width, height);  
  97.                 }  
  98.             }  
  99.         }  
  100.     }  
  101. }
X. BFS
可以只做一次BFS, 把两个出口同时加入队列。
http://jackneus.com/programming-archives/overfencing/
不断的从“搜索点集合”中“拿出”一个点,当这个点的distance+1小于它旁边的另一个点的distance时,就跟新另一个点的distance,且把另一个点加入“搜索点集合”中。当然,这两个点必须是联通的。
直到集合为空,然后找出最大的distance
下面说明算法时间效率为O(w*h)
注意运行时间与向集合中加入点的次数成线性关系
考虑到只有一个出口时,每一个点的distance值仅会被更新一次,而有两个出口时每一个点的distance值最多被更新两次,所以每个点最多被加入集合两次,效率为O(w*h)

import
 java.io.*;
import java.util.*;
public class maze1
{
    private static int w, h;
    private static int[][] distance;//每个点离最近出口的距离
    private static char[][] map;//迷宫地图
    private static int longestDistance;//输出的答案
    private static LinkedList points = new LinkedList();//广度优先搜索需要搜索的点队列
    public static void main(String[] args) throws IOException
    {
        init();
        run();
        output();
        System.exit(0);
    }
    private static void run()
    {
        //当还有需要搜索的点时
        while (!points.isEmpty())
        {
            //获得当前需要搜索的点
            point p = (point)points.getFirst();
            //从队列中移除此点
            points.removeFirst();
            //分别考虑四个方向
            for (int facing = 0; facing < 4; facing++)
            {
                //如果下一步可以走且此点的distance加1小于下一点的distance(发现最优路线)
                if (canMoveAndBester(p, facing))
                {
                    //获得下一点
                    point nextPoint = move(p, facing);
                    //跟新下一点的distance
                    distance[nextPoint.x][nextPoint.y] = distance[p.x][p.y] + 1;
                    //把下一点加入搜索队列
                    points.addLast(nextPoint);
                }
            }
        }
        //计算最大的distance
        longestDistance = calcLongestDistance();
    }
    private static int calcLongestDistance()
    {
        int retDistance = 0;
        for (int i = 0; i < h; i++)
        {
            for (int j = 0; j < w; j++)
            {
                retDistance = Math.max(retDistance, distance[i][j]);
            }
        }
        return retDistance;
    }
    //如果下一点能走且从p点(当前点)走到下一点的方案更好时返回true
    private static boolean canMoveAndBester(point p, int facing)
    {
        boolean retCanMove = true;
        switch (facing)
        {
            case 0:
                //如果走到边界或此方案不是更好的或有障碍物,下面类似
                if ((p.x == 0) || (distance[p.x - 1][p.y] <= distance[p.x][p.y] + 1) || (map[p.x * 2][p.y * 2 + 1] == '-'))
                {
                    retCanMove = false;
                }
                break;
            case 1:
                if ((p.y == w - 1) || (distance[p.x][p.y + 1] <= distance[p.x][p.y] + 1) || (map[p.x * 2 + 1][(p.y + 1) * 2] == '|'))
                {
                    retCanMove = false;
                }
                break;
            case 2:
                if ((p.x == h - 1) || (distance[p.x + 1][p.y] <= distance[p.x][p.y] + 1) || (map[(p.x + 1) * 2][p.y * 2 + 1] == '-'))
                {
                    retCanMove = false;
                }
                break;
            case 3:
                if ((p.y == 0) || (distance[p.x][p.y - 1] <= distance[p.x][p.y] + 1) || (map[p.x * 2 + 1][p.y * 2] == '|'))
                {
                    retCanMove = false;
                }
                break;
        }
        return retCanMove;
    }
    //获得下一点,facing是方向,0、1、2、3分别表示上、右、下、左
    private static point move(point p, int facing)
    {
        point retPoint = null;
        switch (facing)
        {
            case 0:
                retPoint = new point(p.x - 1, p.y);
                break;
            case 1:
                retPoint = new point(p.x, p.y + 1);
                break;
            case 2:
                retPoint = new point(p.x + 1, p.y);
                break;
            case 3:
                retPoint = new point(p.x, p.y - 1);
                break;
        }
        return retPoint;
    }
    private static void init() throws IOException
    {
        BufferedReader f = new BufferedReader(new FileReader("maze1.in"));
        StringTokenizer st = new StringTokenizer(f.readLine());
        w = Integer.parseInt(st.nextToken());
        h = Integer.parseInt(st.nextToken());
        map = new char[h*2+1][w * 2 + 1];
        distance = new int[h][w];
        for (int i = 0; i < h; i++)
        {
            for (int j = 0; j < w; j++)
            {
                distance[i][j] = Integer.MAX_VALUE;
            }
        }
        for (int i = 0; i < h * 2 + 1; i++)
        {
            String str = f.readLine();
            for (int j = 0; j < w * 2 + 1; j++)
            {
                map[i][j] = str.charAt(j);
                if ((i == 0) && (map[i][j] == ' '))
                {
                    distance[0][(j - 1) / 2] = 1;
                    points.addLast(new point(0, (j - 1) / 2));
                }
                if ((i == h * 2) && (map[i][j] == ' '))
                {
                    distance[h - 1][(j - 1) / 2] = 1;
                    points.addLast(new point(h - 1, (j - 1) / 2));
                }
                if ((j == 0) && (map[i][j] == ' '))
                {
                    distance[(i - 1) / 2][0] = 1;
                    points.addLast(new point((i - 1) / 20));
                }
                if ((j == w * 2) && (map[i][j] == ' '))
                {
                    distance[(i - 1) / 2][w - 1] = 1;
                    points.addLast(new point((i - 1) / 2, w - 1));
                }
            }
        }
        f.close();
    }

Read full article from overfencing - codetrick

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts