บทนำ
กำหนด מבוך (Maze) ขนาด N×N จุดเริ่มต้นมุมซ้ายบน จุดหมายมุมขวาล่าง บางช่องเดินได้ (1) บางช่องบล็อก (0) หนูเดินได้เฉพาะขวาหรือลง หาต้องการหาเส้นทางและทำเครื่องหมาย
อินพุตและเอาต์พุต
Input: เมทริกซ์ไบนารี 1=ทางเดิน 0=กำแพง Output: เมทริกซ์แสดงเส้นทางของหนู (1=ทางที่เดิน 0=ไม่เดิน)
อัลกอริทึม
isValid(x, y)
Input: ตำแหน่ง x,y ในמבוך
Output: True ถ้า (x,y) อยู่ในขอบเขตและไม่ถูกบล็อก
Begin
if x,y ในช่วง AND (x,y) ไม่ใช่กำแพง then return true
return false
End
solveRatMaze(x, y)
Input: จุดเริ่มต้น x,y
Output: เส้นทางไปยังจุดหมาย หรือ false
Begin
if (x,y) คือมุมขวาล่าง then mark 1, return true
if isValid(x, y) then
mark (x,y) = 1
if solveRatMaze(x+1, y) return true // เดินขวา
if solveRatMaze(x, y+1) return true // เดินลง
mark (x,y) = 0 // backtrack
return false
return false
End
ตัวอย่างโค้ด (C++)
#include<iostream>
#define N 5
using namespace std;
int maze[N][N] = {
{1, 0, 0, 0, 0},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{1, 1, 1, 1, 1}
};
int sol[N][N];
void showPath() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) cout << sol[i][j] << " ";
cout << endl;
}
}
bool isValidPlace(int x, int y) {
return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1);
}
bool solveRatMaze(int x, int y) {
if(x == N-1 && y == N-1) { sol[x][y] = 1; return true; }
if(isValidPlace(x, y)) {
sol[x][y] = 1;
if (solveRatMaze(x+1, y)) return true;
if (solveRatMaze(x, y+1)) return true;
sol[x][y] = 0; return false;
}
return false;
}
bool findSolution() {
if(!solveRatMaze(0, 0)) { cout << "There is no path"; return false; }
showPath(); return true;
}
int main() { findSolution(); }
ผลลัพธ์
1 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 1 1