본문 바로가기

Algorithm/백준

[백준] 1261번: 알고스팟

www.acmicpc.net/problem/1261

 

1261번: 알고스팟

첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미

www.acmicpc.net

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int MAX = 10000;
const int dx[] = { 0, 0, 1, -1 };
const int dy[] = { 1, -1, 0, 0 };
typedef pair<int, int> P;

int dist[100][100];

struct cmp {
	bool operator()(P a, P b) {
		return dist[a.first][a.second] > dist[b.first][b.second];
	}
};

int main() {
	int m, n;
	int miro[100][100];
	scanf("%d %d", &m, &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%1d", &miro[i][j]);
		}
	}
	bool visited[100][100] = { 0, };

	priority_queue<P, vector<P>, cmp> pq;

	fill(&dist[0][0], &dist[99][99] + 1, MAX);
	dist[0][0] = 0;

	pq.push(P(0, 0));

	while (!pq.empty()) {
		int x = pq.top().first;
		int y = pq.top().second;

		if (visited[x][y]) {
			pq.pop();
			continue;
		}

		visited[x][y] = true;
		pq.pop();

		for (int i = 0; i < 4; i++) {
			int nextX = x + dx[i];
			int nextY = y + dy[i];
			if (nextX < 0 || nextX >= n || nextY < 0 || nextY >= m) continue;

			if (!visited[nextX][nextY] && dist[x][y] + miro[nextX][nextY] < dist[nextX][nextY]) {
				dist[nextX][nextY] = dist[x][y] + miro[nextX][nextY];
				pq.push(P(nextX, nextY));
			}
		}
	}

	printf("%d", dist[n - 1][m - 1]);
}

 

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int MAX = 10000;
const int dx[] = { 0, 0, 1, -1 };
const int dy[] = { 1, -1, 0, 0 };
typedef pair<int, int> P;

int main() {
	int m, n;
	int miro[100][100];
	scanf("%d %d", &m, &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%1d", &miro[i][j]);
		}
	}

	int dist[100][100];
	fill(&dist[0][0], &dist[99][99] + 1, MAX);
	dist[0][0] = 0;

	queue<P> q;
	q.push(P(0, 0));

	while (!q.empty()) {
		int x = q.front().first;
		int y = q.front().second;
		q.pop();

		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];

			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
			if (dist[x][y] + miro[nx][ny] < dist[nx][ny]) {
				dist[nx][ny] = dist[x][y] + miro[nx][ny];
				q.push(P(nx, ny));
			};
		}
	}
    
	printf("%d", dist[n - 1][m - 1]);
}

 

위에꺼는 다익스트라, 아래꺼는 BFS + 메모이제이션 이라고 생각하는데.. 맞나?

나중에 시간날 때 시간복잡도도 계산해봐야겠다.

'Algorithm > 백준' 카테고리의 다른 글

[백준] 11724번: 연결 요소의 개수  (0) 2020.04.08
[백준] 1012번: 유기농 배추  (0) 2020.04.06
[백준] 1182번: 부분수열의 합  (0) 2020.03.28
[백준] 1874번: 스택 수열  (0) 2020.03.23
[백준] 5076번: Web Pages  (0) 2020.03.22