मैं उठाए गए वर्ग के प्रत्येक पड़ोसी से शुरू करूंगा, और ग्रिड की सीमा तक 'भागने' की कोशिश करूंगा। इस बीच, 'एक्स' के बाद पथ चिह्नित करें। यदि आप बच सकते हैं: प्रत्येक 'एक्स' पूर्ववत करें। यदि आप भाग नहीं सकते हैं, तो '#' से प्रत्येक 'एक्स' को प्रतिस्थापित करें। जैसा कि नीचे दिखाया गया है, मैंने जावा में एक उदाहरण बनाया है।
int W, H;
char[][] input;
final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public void handle(int x, int y) {
// try each neihgbor
for (int[] d : directions) {
if (canEscape(input, x, y)) {
// if we can escape, the path found shouldn't be filled
// so replace the Xes by '.';
handleXes(input, false);
} else {
// if we cannot escape, this is a closed shape, so
// fill with '#'
handleXes(input, true);
}
// note that this can be written more concisely as
// handleXes(input, !canEscape(input, x, y));
}
}
public boolean canEscape(char[][] grid, int x, int y) {
if (isEscape(grid, x, y))
return true
if (isValid(grid, x, y)) {
// mark as visited
grid[x][y] = 'X';
// try each neighbor
for (int[] d : directions) {
if (canEscape(grid, x+d[0], y+d[1]))
return true;
}
}
return false;
}
public boolean isValid(char[][] grid, int x, int y) {
return 0 <= x && x < W && 0 <= y && y < H && grid[x][y] == '.';
}
public boolean isEscape(char[][] grid, int x, int y) {
return (0 == x || x == W-1 || 0 == y || y == H-1) && grid[x][y] == '.';
}
public void handleXes(char[][] grid, boolean fill) {
for (int x = 0; x < W; x++)
for (int y = 0; y < H; y++)
if (grid[x][y] == 'X')
grid[x][y] = fill ? '#' : '.';
}
स्रोत
2013-06-17 14:31:32
यह [प्रोग्रामर] (http://programmers.stackexcahnge.com) पर बेहतर नहीं होगा? – zmo
मुझे लगता है कि, एल्गोरिदम आपके मानचित्र का प्रतिनिधित्व करने के लिए उपयोग की जाने वाली डेटा संरचना पर निर्भर करता है। क्या आप कृपया अपने कार्यान्वयन पर अधिक स्पष्ट हो सकते हैं (चूंकि आपने "ग्राफ" टैग किया है) – ibi0tux
मैं डेटा संरचना के रूप में अप्रत्यक्ष ग्राफ के बारे में सोच रहा हूं, जहां प्रत्येक वर्ग किनारों वाले अन्य लोगों से जुड़ा हुआ है। – Kaltsoon