Approach
Depth-first search
For CCC 2003 S3 - Floor Plan, 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
- 119 lines of Java from the credited upstream file ccc03s3.java.
- The implementation visibly relies on sequence storage.
- 8 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.
12345678910111213 141516 17import java.awt.*;18import hsa.*;19 20public class S3J5Floor21{22 static Console cc;23 static int [] [] house;24 static int r, c;25 26 public static void main (String [] args)27 {28 cc = new Console ();29 30 String line;31 int n, k;32 int [] room;33 int count, largest;34 boolean done;35 36 TextInputFile fi = new TextInputFile ("floor5.in");37 TextOutputFile fo = new TextOutputFile ("floor5.out");38 39 40 41 n = fi.readInt ();42 r = fi.readInt ();43 c = fi.readInt ();44 house = new int [r] [c];45 for (int i = 0 ; i < r ; i++)46 {47 line = fi.readLine ();48 for (int j = 0 ; j < c ; j++)49 if (line.charAt (j) == 'I')50 house [i] [j] = -1;51 else52 house [i] [j] = 0;53 }54 55 56 k = 1;57 for (int i = 0 ; i < r ; i++)58 for (int j = 0 ; j < c ; j++)59 if (house [i] [j] == 0)60 {61 check (i, j, k);62 k++;63 }64 65 66 room = new int [500];67 for (int i = 0 ; i < r ; i++)68 for (int j = 0 ; j < c ; j++)69 if (house [i] [j] > 0)70 room [house [i] [j]]++;71 72 73 count = 0;74 done = false;75 while (!done && n > 0)76 {77 largest = 0;78 for (int i = 0 ; i < 500 ; i++)79 if (room [i] > room [largest])80 largest = i;81 if (room [largest] > 0)82 {83 if (room [largest] <= n)84 {85 n = n - room [largest];86 room [largest] = -1;87 count++;88 }89 else90 done = true;91 }92 else93 done = true;94 }95 96 fo.println (count + " rooms, " + n + " square metre(s) left over");97 98 fi.close ();99 fo.close ();100 }101 102 103 104 105 public static void check (int i, int j, int k)106 {107 if (i >= 0 && i < r && j >= 0 && j < c && house [i] [j] == 0)108 {109 house [i] [j] = k;110 check (i - 1, j, k);111 check (i + 1, j, k);112 check (i, j + 1, k);113 check (i, j - 1, k);114 }115 }116}117 118 119