import java.util.*;
public class main {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.Chap05Example10(15,14,new int[][]{
{0,0,0,0,0,1,1,1,1,0,0,0,0,0},//1
{1,1,1,1,1,1,0,1,1,1,1,1,1,0},//2
{1,1,0,1,1,1,0,1,1,0,1,1,1,0},//3
{1,1,0,1,1,1,0,1,1,0,0,0,0,0},//4
{1,1,0,1,1,1,1,1,1,1,1,1,1,1},//5
{1,1,0,1,1,1,1,1,1,1,1,1,0,0},//6
{1,1,0,0,0,0,0,0,0,1,1,1,1,1},//7
{0,1,1,1,1,1,1,1,1,1,1,1,1,1},//8
{0,0,0,0,0,0,0,0,0,1,1,1,1,1},//9
{0,1,1,1,1,1,1,1,1,1,1,0,0,0},//10
{0,0,0,1,1,1,1,1,1,1,1,0,0,0},//11
{0,0,0,0,0,0,0,1,1,1,1,0,0,0},//12
{1,1,1,1,1,1,1,1,1,1,0,0,1,1},//13
{1,1,1,0,0,0,1,1,1,1,1,1,1,1},//14
{1,1,1,0,0,0,1,1,1,1,1,1,1,1}//15
}));
System.out.println(s.Chap05Example11(5,6, new int[][]{
{1,0,1,0,1,0},
{1,1,1,1,1,1},
{0,0,0,0,0,1},
{1,1,1,1,1,1},
{1,1,1,1,1,1}
}));
}
}
class Solution {
public int Chap05Example10(int m, int n, int[][] blocks) {
int answer = 0;
int[][] visited = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (visited[i][j] == 0 && blocks[i][j] == 0) {
Chap05Example10_DFS(i, j, blocks, visited);
answer++;
}
}
}
return answer;
}
public void Chap05Example10_DFS(int y, int x, int[][] blocks, int[][] visited) {
int[][] move = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
visited[y][x] = 1;
int tmpY = 0;
int tmpX = 0;
for (int i = 0; i < move.length; ++i) {
tmpY = y + move[i][0];
tmpX = x + move[i][1];
if (tmpY < blocks.length && tmpX < blocks[0].length && tmpY >= 0 && tmpX >= 0 && blocks[tmpY][tmpX] == 0 && visited[tmpY][tmpX] == 0) {
Chap05Example10_DFS(tmpY, tmpX, blocks, visited);
}
}
}
public int Chap05Example11(int m, int n, int[][] map) {
int[][] visited = new int[m][n];
int[][] move = new int[][]{{-1,0}, {1,0}, {0,1}, {0,-1}};
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0, 1});
while (!queue.isEmpty()) {
int[] tile = queue.poll();
visited[tile[0]][tile[1]] = 1;
if (tile[0] == m-1 && tile[1] == n-1) {
return tile[2];
}
for(int i = 0; i<move.length;++i) {
int tmpY = tile[0]+move[i][0];
int tmpX = tile[1]+move[i][1];
if(tmpY >= 0 && tmpX >= 0 && tmpY < m && tmpX < n && visited[tmpY][tmpX] == 0 && map[tmpY][tmpX] == 1) {
queue.add(new int[]{tmpY, tmpX, tile[2]+1});
}
}
}
return 0;
}
}
---
이제는 지겹도록 본 DFS, BFS
타일에서의 (-1, 0), (1, 0), (0, 1),(0, -1) 처럼 이동과 관련된 것은 배열에 미리 담아두고 푸는게 실수를 줄일 수 있다고 해서 의식해서 써보고 있다.