Approach
Depth-first search
For CCC 2008 S3 - Maze, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 97 lines of Java from the credited upstream file ccc08s3.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234567891011121314151617181920212223242526272829 30import java.awt.*;31import hsa.*;32 33public class CCC2008S3Maze34{35 static Console c;36 static char[] [] maze;37 static int[] [] grid;38 static int row, col;39 40 public static void traverse (int r, int c, int x)41 {42 if (r >= 0 && r < row && c >= 0 && c < col)43 if (grid [r] [c] >= 0 && x < grid [r] [c])44 if (maze [r] [c] == '*')45 grid [r] [c] = -1;46 else if (maze [r] [c] == '+')47 {48 grid [r] [c] = x;49 traverse (r - 1, c, x + 1);50 traverse (r + 1, c, x + 1);51 traverse (r, c - 1, x + 1);52 traverse (r, c + 1, x + 1);53 }54 else if (maze [r] [c] == '|')55 {56 grid [r] [c] = x;57 traverse (r - 1, c, x + 1);58 traverse (r + 1, c, x + 1);59 }60 else if (maze [r] [c] == '-')61 {62 grid [r] [c] = x;63 traverse (r, c - 1, x + 1);64 traverse (r, c + 1, x + 1);65 }66 }67 68 69 public static void main (String[] args)70 {71 int t;72 c = new Console ();73 TextInputFile f = new TextInputFile ("s3.5.in");74 t = f.readInt ();75 for (int k = 0 ; k < t ; k++)76 {77 row = f.readInt ();78 col = f.readInt ();79 maze = new char [row] [col];80 grid = new int [row] [col];81 for (int i = 0 ; i < row ; i++)82 for (int j = 0 ; j < col ; j++)83 maze [i] [j] = f.readChar ();84 for (int i = 0 ; i < row ; i++)85 for (int j = 0 ; j < col ; j++)86 grid [i] [j] = 99999;87 traverse (0, 0, 1);88 if (grid [row - 1] [col - 1] > 0 && grid [row - 1] [col - 1] < 99999)89 c.println (grid [row - 1] [col - 1]);90 else91 c.println (-1);92 }93 }94}95 96 97