// Project: rRcursion // Module: maze // Source code file: MyFrame.java // Compute and display the path that // connects the start point to the end point. // Show solution in yellow. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.StringTokenizer; public class MyPanel extends JPanel { private int[][] array; private int width, height; private int xStart, yStart, xEnd, yEnd; private boolean done; private BufferedReader br; public MyPanel(int w, int h, BufferedReader b) { width = w; height = h; br = b; addMouseListener(new MouseDetector()); done = false; array = new int[width][height]; initialize(); repaint(); } public void initialize() { int x, y; StringTokenizer st; String line = null; char symbol; try { line = br.readLine(); } catch(IOException e) { System.out.println(e); } st = new StringTokenizer(line, " "); xStart = Integer.parseInt(st.nextToken()); yStart = Integer.parseInt(st.nextToken()); xEnd = Integer.parseInt(st.nextToken()); yEnd = Integer.parseInt(st.nextToken()); for(y = 0; y <= height - 1; y++) { try { line = br.readLine(); } catch(IOException e) { System.out.println(e); } for(x = 0; x <= width - 1; x++) { symbol = line.charAt(x); if (symbol == '*') array[x][y] = 1; else if (symbol == ' ') array[x][y] = 0; } repaint(); } } public void search(int x, int y) { if (done) return; else if (x == xEnd && y == yEnd) { done = true; return; } else if (array[x][y] == 0) { array[x][y] = 2; search(x + 1, y); search(x, y -1); search(x - 1, y); search(x, y + 1); if (!done) array[x][y] = 0; } return; } public void paintComponent(Graphics g) { super.paintComponent(g); int x, y, value; setBackground(Color.white); for(x = 0; x <= width - 1; x++) for(y = 0; y <= height - 1; y++) if (array[x][y] == 1) { g.setColor(Color.black); g.fillRect(8*x, 8*y, 8, 8); } else if (array[x][y] == 0) { g.setColor(Color.white); g.fillRect(8*x, 8*y, 8, 8); } else if (array[x][y] == 2) { g.setColor(Color.yellow); g.fillRect(8*x, 8*y, 8, 8); } g.setColor(Color.green); g.fillRect(8*xStart, 8*yStart, 8, 8); g.setColor(Color.red); g.fillRect(8*xEnd, 8*yEnd, 8, 8); } private class MouseDetector implements MouseListener { public void mouseReleased(MouseEvent e) { search(xStart, yStart); repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} } }