Skip to content

Commit

Permalink
Merge pull request #34 from AlgoLeadMe/9-mong3125
Browse files Browse the repository at this point in the history
9-mong3125
  • Loading branch information
mong3125 committed Mar 20, 2024
2 parents 75b397f + 22693d2 commit b45efe9
Showing 1 changed file with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class BOJ2178_๋ฏธ๋กœํƒ์ƒ‰ํ•˜๊ธฐ {

static int n;
static int m;

static boolean[][] field;
static boolean[][] visited;

static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
public static void main(String[] args) throws IOException {
// ์ž…๋ ฅ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

n = Integer.parseInt(st.nextToken()); // ์„ธ๋กœ ํฌ๊ธฐ
m = Integer.parseInt(st.nextToken()); // ๊ฐ€๋กœ ํฌ๊ธฐ

// ๋ฏธ๋กœ ์„ ์–ธ
field = new boolean[n][m];
visited = new boolean[n][m];

// ๋ฏธ๋กœ ์ž…๋ ฅ
for (int i = 0; i < n; i++) {
String line = br.readLine();
for (int j = 0; j < m; j++) {
field[i][j] = line.charAt(j) == '1';
}
}

// ๋ฌธ์ œ ํ•ด๊ฒฐ
int answer = bfs(0, 0);

// ์ถœ๋ ฅ
System.out.println(answer);
}

public static int bfs(int i, int j) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{i, j, 1});
visited[i][j] = true;

while (!queue.isEmpty()) {
int[] now = queue.poll();

if (now[0] == n - 1 && now[1] == m - 1) {
return now[2];
}

for (int k = 0; k < 4; k++) {
int x = now[0] + dx[k];
int y = now[1] + dy[k];

if (isInRange(x, y)) {
if (!visited[x][y] && field[x][y]) {
queue.add(new int[]{x, y, now[2] + 1});
visited[x][y] = true;
}
}
}
}

return 0;
}

public static boolean isInRange(int i, int j) {
return 0 <= i && i < n && 0 <= j && j < m;
}
}

0 comments on commit b45efe9

Please sign in to comment.